├── .husky └── pre-commit ├── pnpm-workspace.yaml ├── packages ├── core │ ├── tsconfig.eslint.json │ ├── tsconfig.json │ ├── src │ │ ├── builder.ts │ │ ├── translator.ts │ │ ├── index.ts │ │ ├── parsers │ │ │ ├── defaultInstructionParsers.ts │ │ │ └── ObjectQueryParser.ts │ │ ├── types.ts │ │ ├── Condition.ts │ │ ├── utils.ts │ │ └── interpreter.ts │ ├── spec │ │ ├── specHelper.ts │ │ ├── ast.spec.ts │ │ ├── translator.spec.ts │ │ ├── optimizedCompoundCondition.spec.ts │ │ ├── interpreter.spec.ts │ │ └── ObjectQueryParser.spec.ts │ ├── NOTICE │ ├── package.json │ ├── README.md │ ├── CHANGELOG.md │ └── LICENSE ├── js │ ├── tsconfig.eslint.json │ ├── spec │ │ ├── specHelper.ts │ │ ├── fieldConditionInterpreter.behavior.ts │ │ └── getObjectField.spec.ts │ ├── tsconfig.json │ ├── src │ │ ├── index.ts │ │ ├── defaults.ts │ │ ├── types.ts │ │ ├── interpreter.ts │ │ ├── utils.ts │ │ └── interpreters.ts │ ├── NOTICE │ ├── package.json │ ├── README.md │ ├── CHANGELOG.md │ └── LICENSE ├── mongo │ ├── tsconfig.eslint.json │ ├── spec │ │ ├── specHelper.ts │ │ └── MongoQueryParser.spec.ts │ ├── tsconfig.json │ ├── src │ │ ├── index.ts │ │ ├── utils.ts │ │ ├── MongoQueryParser.ts │ │ ├── types.ts │ │ └── instructions.ts │ ├── NOTICE │ ├── package.json │ ├── README.md │ └── CHANGELOG.md ├── sql │ ├── tsconfig.eslint.json │ ├── src │ │ ├── index.ts │ │ ├── defaults.ts │ │ ├── lib │ │ │ ├── objection.ts │ │ │ ├── sequelize.ts │ │ │ ├── mikro-orm.ts │ │ │ └── typeorm.ts │ │ ├── dialects.ts │ │ ├── interpreters.ts │ │ └── interpreter.ts │ ├── typeorm │ │ └── package.json │ ├── mikro-orm │ │ └── package.json │ ├── objection │ │ └── package.json │ ├── sequelize │ │ └── package.json │ ├── tsconfig.json │ ├── spec │ │ ├── specHelper.ts │ │ ├── sequelize.spec.ts │ │ ├── objection.spec.ts │ │ ├── mikro-orm.spec.ts │ │ └── typeorm.spec.ts │ ├── NOTICE │ ├── package.json │ └── README.md └── mongo2js │ ├── tsconfig.eslint.json │ ├── src │ ├── index.ts │ └── factory.ts │ ├── spec │ ├── specHelper.ts │ ├── squire.spec.ts │ └── guard.spec.ts │ ├── tsconfig.json │ ├── NOTICE │ ├── package.json │ ├── CHANGELOG.md │ └── README.md ├── tsconfig.eslint.json ├── tsconfig.json ├── babel.config.js ├── .github └── workflows │ └── main.yml ├── semantic-release.js ├── .gitignore ├── package.json ├── README.md ├── rollup.config.js ├── eslint.config.mjs └── CONTRIBUTING.md /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | npx lint-staged 2 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - packages/* 3 | -------------------------------------------------------------------------------- /packages/core/tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.eslint.json" 3 | } 4 | -------------------------------------------------------------------------------- /packages/js/tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.eslint.json" 3 | } 4 | -------------------------------------------------------------------------------- /packages/mongo/tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.eslint.json" 3 | } 4 | -------------------------------------------------------------------------------- /packages/sql/tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.eslint.json" 3 | } 4 | -------------------------------------------------------------------------------- /packages/mongo2js/tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.eslint.json" 3 | } 4 | -------------------------------------------------------------------------------- /packages/mongo2js/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './factory'; 2 | export * from '@ucast/js'; 3 | export * from '@ucast/mongo'; 4 | export * from '@ucast/core'; 5 | -------------------------------------------------------------------------------- /packages/sql/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './interpreters'; 2 | export * from './interpreter'; 3 | export * from './defaults'; 4 | export * from './dialects'; 5 | -------------------------------------------------------------------------------- /tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": [ 4 | "**/src/**/*.ts", 5 | "**/spec/**/*.ts", 6 | "**/*.js" 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /packages/sql/src/defaults.ts: -------------------------------------------------------------------------------- 1 | import * as interpreters from './interpreters'; 2 | 3 | export const allInterpreters = { 4 | ...interpreters, 5 | in: interpreters.within, 6 | }; 7 | -------------------------------------------------------------------------------- /packages/js/spec/specHelper.ts: -------------------------------------------------------------------------------- 1 | import chai from 'chai' 2 | import spies from 'chai-spies' 3 | 4 | chai.use(spies) 5 | 6 | export const expect = chai.expect 7 | export const spy = chai.spy 8 | -------------------------------------------------------------------------------- /packages/js/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig", 3 | "include": [ 4 | "src/*" 5 | ], 6 | "compilerOptions": { 7 | "outDir": "dist/types", 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /packages/core/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig", 3 | "include": [ 4 | "src/*" 5 | ], 6 | "compilerOptions": { 7 | "outDir": "dist/types", 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /packages/mongo/spec/specHelper.ts: -------------------------------------------------------------------------------- 1 | import chai from 'chai' 2 | import spies from 'chai-spies' 3 | 4 | chai.use(spies) 5 | 6 | export const expect = chai.expect 7 | export const spy = chai.spy 8 | -------------------------------------------------------------------------------- /packages/mongo/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig", 3 | "include": [ 4 | "src/*" 5 | ], 6 | "compilerOptions": { 7 | "outDir": "dist/types", 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /packages/js/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './interpreters'; 2 | export * from './interpreter'; 3 | export * from './defaults'; 4 | export type { JsInterpretationOptions, JsInterpreter } from './types'; 5 | -------------------------------------------------------------------------------- /packages/mongo2js/spec/specHelper.ts: -------------------------------------------------------------------------------- 1 | import chai from 'chai' 2 | import spies from 'chai-spies' 3 | 4 | chai.use(spies) 5 | 6 | export const expect = chai.expect 7 | export const spy = chai.spy 8 | -------------------------------------------------------------------------------- /packages/mongo2js/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig", 3 | "include": [ 4 | "src/*" 5 | ], 6 | "compilerOptions": { 7 | "outDir": "dist/types", 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /packages/sql/typeorm/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ucast/sql-typeorm", 3 | "private": true, 4 | "typings": "../dist/types/lib/typeorm.d.ts", 5 | "main": "../dist/es6c/lib/typeorm.js", 6 | "es2015": "../dist/es6m/lib/typeorm.js" 7 | } 8 | -------------------------------------------------------------------------------- /packages/sql/mikro-orm/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ucast/sql-mikro-orm", 3 | "private": true, 4 | "typings": "../dist/types/lib/mikro-orm.d.ts", 5 | "main": "../dist/es6c/lib/mikro-orm.js", 6 | "es2015": "../dist/es6m/lib/mikro-orm.js" 7 | } 8 | -------------------------------------------------------------------------------- /packages/sql/objection/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ucast/sql-objection", 3 | "private": true, 4 | "typings": "../dist/types/lib/objection.d.ts", 5 | "main": "../dist/es6c/lib/objection.js", 6 | "es2015": "../dist/es6m/lib/objection.js" 7 | } 8 | -------------------------------------------------------------------------------- /packages/sql/sequelize/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ucast/sql-sequelize", 3 | "private": true, 4 | "typings": "../dist/types/lib/sequelize.d.ts", 5 | "main": "../dist/es6c/lib/sequelize.js", 6 | "es2015": "../dist/es6m/lib/sequelize.js" 7 | } 8 | -------------------------------------------------------------------------------- /packages/sql/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig", 3 | "include": [ 4 | "src/**/*" 5 | ], 6 | "exclude": [ 7 | "src/lib/mikro-orm.ts" // TODO: upgrade mikro-orm to v6 8 | ], 9 | "compilerOptions": { 10 | "outDir": "dist/types" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "moduleResolution": "node", 5 | "strict": true, 6 | "declaration": true, 7 | "emitDeclarationOnly": true, 8 | "noErrorTruncation": true, 9 | "esModuleInterop": true 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /packages/js/src/defaults.ts: -------------------------------------------------------------------------------- 1 | import { createJsInterpreter } from './interpreter'; 2 | import * as interpreters from './interpreters'; 3 | 4 | export const allInterpreters = { 5 | ...interpreters, 6 | in: interpreters.within, 7 | }; 8 | export const interpret = createJsInterpreter(allInterpreters); 9 | -------------------------------------------------------------------------------- /packages/mongo/src/index.ts: -------------------------------------------------------------------------------- 1 | import * as instructions from './instructions'; 2 | 3 | export const allParsingInstructions = instructions; 4 | export * from './instructions'; 5 | export * from './MongoQueryParser'; 6 | export * from './types'; 7 | export { defaultInstructionParsers as defaultParsers } from '@ucast/core'; 8 | -------------------------------------------------------------------------------- /packages/sql/spec/specHelper.ts: -------------------------------------------------------------------------------- 1 | import chai from 'chai' 2 | import spies from 'chai-spies' 3 | 4 | chai.use(spies) 5 | 6 | export const expect = chai.expect 7 | export const spy = chai.spy 8 | export function linearize(value: TemplateStringsArray) { 9 | return value.join('').replace(/[\n\r] */g, ' ').trim() 10 | } 11 | -------------------------------------------------------------------------------- /packages/core/src/builder.ts: -------------------------------------------------------------------------------- 1 | import { Condition } from './Condition'; 2 | import { optimizedCompoundCondition } from './utils'; 3 | 4 | export const buildAnd = (conditions: Condition[]) => optimizedCompoundCondition('and', conditions); 5 | export const buildOr = (conditions: Condition[]) => optimizedCompoundCondition('or', conditions); 6 | -------------------------------------------------------------------------------- /packages/js/src/types.ts: -------------------------------------------------------------------------------- 1 | import { Condition, ITSELF, InterpretationContext } from '@ucast/core'; 2 | 3 | export interface JsInterpretationOptions { 4 | get(object: any, field: string | typeof ITSELF): any 5 | compare(a: T, b: T): 1 | -1 | 0 6 | } 7 | 8 | export type JsInterpreter = ( 9 | node: N, 10 | value: Value, 11 | context: InterpretationContext> & JsInterpretationOptions 12 | ) => boolean; 13 | -------------------------------------------------------------------------------- /packages/core/spec/specHelper.ts: -------------------------------------------------------------------------------- 1 | import chai from 'chai' 2 | import spies from 'chai-spies' 3 | 4 | chai.use(spies) 5 | 6 | export const expect = chai.expect 7 | 8 | interface Spy extends ChaiSpies.Spy { 9 | calls(fn: (...args: any) => any): unknown[][]; 10 | } 11 | 12 | export const spy = chai.spy as Spy 13 | 14 | spy.calls = (fn: (...args: any) => any) => { 15 | const meta = (fn as any).__spy 16 | 17 | if (!meta) { 18 | throw new Error('Trying to get calls of not a spy') 19 | } 20 | 21 | return meta.calls 22 | } 23 | -------------------------------------------------------------------------------- /packages/mongo/src/utils.ts: -------------------------------------------------------------------------------- 1 | import { MongoQueryOperators } from './types'; 2 | 3 | export const hasOwn = Object.hasOwn || 4 | Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); 5 | 6 | export function hasOperators(value: any): value is MongoQueryOperators { 7 | if (!value || value && value.constructor !== Object) { 8 | return false; 9 | } 10 | 11 | for (const prop in value) { 12 | if (hasOwn(value, prop) && prop[0] === '$') { 13 | return true; 14 | } 15 | } 16 | 17 | return false; 18 | } 19 | -------------------------------------------------------------------------------- /packages/js/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Sergii Stotskyi 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /packages/core/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Sergii Stotskyi 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /packages/mongo/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Sergii Stotskyi 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /packages/sql/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Sergii Stotskyi 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /packages/mongo2js/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Sergii Stotskyi 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /packages/core/src/translator.ts: -------------------------------------------------------------------------------- 1 | import { Condition } from './Condition'; 2 | import { Parse } from './types'; 3 | import { AnyInterpreter } from './interpreter'; 4 | 5 | type Bound = T extends (first: Condition, ...args: infer A) => any 6 | ? { (...args: A): ReturnType, ast: Condition } 7 | : never; 8 | 9 | export function createTranslatorFactory( 10 | parse: Parse, 11 | interpret: Interpreter 12 | ) { 13 | return (query: Lang, ...args: unknown[]): Bound => { 14 | const ast = parse(query, ...args); 15 | const translate = (interpret as any).bind(null, ast); 16 | translate.ast = ast; 17 | return translate; 18 | }; 19 | } 20 | -------------------------------------------------------------------------------- /packages/core/src/index.ts: -------------------------------------------------------------------------------- 1 | import { ObjectQueryParser } from './parsers/ObjectQueryParser'; 2 | 3 | export * from './Condition'; 4 | export * from './types'; 5 | export * from './interpreter'; 6 | export * from './translator'; 7 | export * from './builder'; 8 | export { 9 | isCompound, 10 | hasOperators, 11 | identity, 12 | object, 13 | optimizedCompoundCondition, 14 | ignoreValue, 15 | } from './utils'; 16 | export type { 17 | IgnoreValue 18 | } from './utils'; 19 | export * from './parsers/ObjectQueryParser'; 20 | export * from './parsers/defaultInstructionParsers'; 21 | /** 22 | * @deprecated use `ObjectQueryParser#parseInstruction` instead 23 | * TODO(major): remove 24 | */ 25 | export const parseInstruction = (ObjectQueryParser.prototype as any).parseInstruction; 26 | -------------------------------------------------------------------------------- /packages/core/spec/ast.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai' 2 | import { FieldCondition, CompoundCondition, Condition } from '../src' 3 | 4 | describe('AST', () => { 5 | describe('CompoundCondition', () => { 6 | it('throws exception if receives non array', () => { 7 | expect(() => new CompoundCondition('and', null as unknown as Condition[])).to.throw(Error) 8 | }) 9 | }) 10 | 11 | describe('FieldCondition', () => { 12 | it('has "operator" property', () => { 13 | const node = new FieldCondition('eq', 'name', 'test') 14 | expect(node.operator).to.equal('eq') 15 | }) 16 | 17 | it('has "field" property', () => { 18 | const node = new FieldCondition('eq', 'name', 'test') 19 | expect(node.field).to.equal('name') 20 | }) 21 | 22 | it('has "value" property', () => { 23 | const node = new FieldCondition('eq', 'name', 'test') 24 | expect(node.value).to.equal('test') 25 | }) 26 | }) 27 | }) 28 | -------------------------------------------------------------------------------- /packages/mongo/src/MongoQueryParser.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Condition, 3 | buildAnd as and, 4 | ParsingInstruction, 5 | ObjectQueryParser, 6 | FieldQueryOperators, 7 | } from '@ucast/core'; 8 | import { MongoQuery } from './types'; 9 | 10 | export interface ParseOptions { 11 | field: string 12 | } 13 | 14 | export class MongoQueryParser extends ObjectQueryParser> { 15 | constructor(instructions: Record) { 16 | super(instructions, { 17 | defaultOperatorName: '$eq', 18 | operatorToConditionName: name => name.slice(1), 19 | }); 20 | } 21 | 22 | parse, FQ extends FieldQueryOperators = FieldQueryOperators>( 23 | query: Q | FQ, 24 | options?: ParseOptions 25 | ): Condition { 26 | if (options && options.field) { 27 | return and(this.parseFieldOperators(options.field, query as FQ)); 28 | } 29 | 30 | return super.parse(query); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /packages/mongo/spec/MongoQueryParser.spec.ts: -------------------------------------------------------------------------------- 1 | import { FieldCondition } from '@ucast/core' 2 | import { MongoQueryParser, $eq } from '../src' 3 | import { expect } from './specHelper' 4 | 5 | describe('MongoQueryParser', () => { 6 | it('removes `$` prefix from resulting condition operator name', () => { 7 | const parser = new MongoQueryParser({ $eq }) 8 | const ast = parser.parse({ age: { $eq: 1 } }) 9 | 10 | expect(ast.operator).to.equal('eq') 11 | }) 12 | 13 | it('uses `$eq` as default operator', () => { 14 | const parser = new MongoQueryParser({ $eq }) 15 | const ast = parser.parse({ age: 1 }) 16 | 17 | expect(ast.operator).to.equal('eq') 18 | }) 19 | 20 | it('allows to parse field level operators when field is specified in context', () => { 21 | const parser = new MongoQueryParser({ $eq }) 22 | const ast = parser.parse({ $eq: 5 }, { field: 'name' }) as FieldCondition 23 | 24 | expect(ast.operator).to.equal('eq') 25 | expect(ast.value).to.equal(5) 26 | expect(ast.field).to.equal('name') 27 | }) 28 | }) 29 | -------------------------------------------------------------------------------- /packages/core/src/parsers/defaultInstructionParsers.ts: -------------------------------------------------------------------------------- 1 | import { 2 | FieldCondition, 3 | CompoundCondition, 4 | DocumentCondition, 5 | } from '../Condition'; 6 | import { 7 | DocumentInstruction, 8 | CompoundInstruction, 9 | FieldInstruction, 10 | } from '../types'; 11 | 12 | interface DefaultParsers { 13 | compound: Exclude, 14 | field: Exclude, 15 | document: Exclude 16 | } 17 | 18 | export const defaultInstructionParsers: DefaultParsers = { 19 | compound(instruction, value, context) { 20 | const queries = Array.isArray(value) ? value : [value]; 21 | const conditions = queries.map(query => context.parse(query)); 22 | return new CompoundCondition(instruction.name, conditions); 23 | }, 24 | field(instruction, value, context) { 25 | return new FieldCondition(instruction.name, context.field, value); 26 | }, 27 | document(instruction, value) { 28 | return new DocumentCondition(instruction.name, value); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /packages/core/spec/translator.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai' 2 | import { createTranslatorFactory, FieldCondition, createInterpreter, InterpretationContext } from '../src' 3 | 4 | type Interpreter = ( 5 | node: FieldCondition, 6 | value: string, 7 | context: InterpretationContext 8 | ) => boolean 9 | 10 | describe('createTranslatorFactory', () => { 11 | const parse = (value: string) => new FieldCondition('eq', 'title', value) 12 | const interpret = createInterpreter({ 13 | eq(node: FieldCondition, value: string) { 14 | return node.value === value 15 | } 16 | }) 17 | 18 | it('creates a factory function that parses and interprets query', () => { 19 | const factory = createTranslatorFactory(parse, interpret) 20 | const translate = factory('test') 21 | 22 | expect(factory).to.be.a('function') 23 | expect(translate('test')).to.be.true 24 | expect(translate('test2')).to.be.false 25 | }) 26 | 27 | it('adds `ast` property to resulting function', () => { 28 | const factory = createTranslatorFactory(parse, interpret) 29 | const translate = factory('test') 30 | 31 | expect(translate.ast).to.deep.equal(parse('test')) 32 | }) 33 | }) 34 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | const CONFIG = { 2 | default: { 3 | plugins: [ 4 | ['@babel/plugin-transform-typescript', { 5 | allowDeclareFields: true 6 | }], 7 | ['@babel/plugin-proposal-class-properties', { 8 | loose: true 9 | }], 10 | ], 11 | }, 12 | es6: { 13 | plugins: [ 14 | ['@babel/plugin-proposal-object-rest-spread', { 15 | loose: true, 16 | useBuiltIns: true 17 | }] 18 | ] 19 | }, 20 | es5: { 21 | presets: [ 22 | ['@babel/preset-env', { 23 | modules: false, 24 | loose: true, 25 | targets: { 26 | browsers: ['last 3 versions'] 27 | } 28 | }], 29 | ], 30 | }, 31 | }; 32 | 33 | function config(name) { 34 | if (name === 'default' || !CONFIG[name]) { 35 | return CONFIG.default; 36 | } 37 | 38 | const { presets = [], plugins = [] } = CONFIG[name]; 39 | 40 | return { 41 | presets: presets.concat(CONFIG.default.presets || []), 42 | plugins: plugins.concat(CONFIG.default.plugins || []), 43 | }; 44 | } 45 | 46 | module.exports = (api) => { 47 | let format; 48 | api.caller(caller => format = caller.output || process.env.NODE_ENV); 49 | api.cache.using(() => format); 50 | 51 | return config(format); 52 | }; 53 | -------------------------------------------------------------------------------- /packages/core/src/types.ts: -------------------------------------------------------------------------------- 1 | import { Condition } from './Condition'; 2 | 3 | export type Named = T & { name: Name }; 4 | export type Parse = (query: T, ...args: any[]) => Condition; 5 | export type ParsingContext = T & { parse: Parse }; 6 | 7 | export interface ParsingInstruction { 8 | type: string 9 | validate?(instruction: Named, value: T): void 10 | parse?(instruction: Named, value: T, context: ParsingContext): Condition 11 | } 12 | 13 | export interface CompoundInstruction< 14 | T = unknown, 15 | C extends {} = {} 16 | > extends ParsingInstruction { 17 | type: 'compound', 18 | } 19 | 20 | export interface DocumentInstruction< 21 | T = unknown, 22 | C extends {} = {} 23 | > extends ParsingInstruction { 24 | type: 'document', 25 | } 26 | 27 | export interface FieldParsingContext { 28 | field: string 29 | } 30 | 31 | export interface FieldInstruction< 32 | T = unknown, 33 | C extends FieldParsingContext = FieldParsingContext 34 | > extends ParsingInstruction { 35 | type: 'field', 36 | } 37 | 38 | export type NamedInstruction = Named; 39 | export type Comparable = number | string | Date; 40 | -------------------------------------------------------------------------------- /packages/sql/src/lib/objection.ts: -------------------------------------------------------------------------------- 1 | import { Condition } from '@ucast/core'; 2 | import { Model, QueryBuilder } from 'objection'; 3 | import { 4 | createSqlInterpreter, 5 | allInterpreters, 6 | SqlOperator, 7 | createDialects, 8 | mysql, 9 | } from '../index'; 10 | 11 | function joinRelation(relationName: string, query: QueryBuilder) { 12 | if (!query.modelClass().getRelation(relationName)) { 13 | return false; 14 | } 15 | 16 | query.joinRelated(relationName); 17 | return true; 18 | } 19 | 20 | const dialects = createDialects({ 21 | joinRelation, 22 | paramPlaceholder: mysql.paramPlaceholder, 23 | }); 24 | 25 | export function createInterpreter(interpreters: Record>) { 26 | const interpretSQL = createSqlInterpreter(interpreters); 27 | return (condition: Condition, query: QueryBuilder) => { 28 | const dialect = query.modelClass().knex().client.config.client as keyof typeof dialects; 29 | const options = dialects[dialect]; 30 | 31 | if (!options) { 32 | throw new Error('Unsupported database dialect'); 33 | } 34 | 35 | const [sql, params] = interpretSQL(condition, options, query); 36 | return query.whereRaw(sql, params); 37 | }; 38 | } 39 | 40 | export const interpret = createInterpreter(allInterpreters); 41 | -------------------------------------------------------------------------------- /packages/core/spec/optimizedCompoundCondition.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai' 2 | import { optimizedCompoundCondition, FieldCondition, CompoundCondition } from '../src' 3 | 4 | describe('optimizedCompoundCondition', () => { 5 | const child = new FieldCondition('eq', 'x', 1) 6 | 7 | it('returns child condition if there is only 1 condition passed', () => { 8 | const ast = optimizedCompoundCondition('and', [child]) 9 | expect(ast).to.equal(child) 10 | }) 11 | 12 | it('merges children conditions with the same name recursively', () => { 13 | const ast = optimizedCompoundCondition('and', [ 14 | new CompoundCondition('and', [ 15 | new CompoundCondition('and', [child]), 16 | child 17 | ]), 18 | child 19 | ]) 20 | 21 | expect(ast).to.deep.equal(new CompoundCondition('and', [child, child, child])) 22 | }) 23 | 24 | it('does not merge compound conditions with another operator name', () => { 25 | const ast = optimizedCompoundCondition('and', [ 26 | new CompoundCondition('and', [ 27 | new CompoundCondition('or', [child]), 28 | child 29 | ]), 30 | child 31 | ]) 32 | 33 | expect(ast).to.deep.equal(new CompoundCondition('and', [ 34 | new CompoundCondition('or', [child]), 35 | child, 36 | child 37 | ])) 38 | }) 39 | }) 40 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | paths: 7 | - .github/workflows/main.yml 8 | - packages/**/*.{js,ts,json} 9 | - babel.config.js 10 | - package.json 11 | - pnpm-lock.yaml 12 | - .eslintrc 13 | pull_request: 14 | 15 | jobs: 16 | build: 17 | runs-on: ubuntu-latest 18 | strategy: 19 | matrix: 20 | node: 21 | - 20 # April 30, 2026 22 | - 22 # April 30, 2027 23 | - latest 24 | steps: 25 | - uses: actions/checkout@v5 26 | - uses: pnpm/action-setup@v4 27 | with: 28 | version: 9.15.3 29 | - name: Cache dependencies 30 | uses: actions/cache@v4 31 | env: 32 | cache-name: ucast-deps 33 | with: 34 | path: ~/.pnpm-store 35 | key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('./pnpm-lock.yaml') }} 36 | restore-keys: | 37 | ${{ runner.os }}-build-${{ env.cache-name }}- 38 | ${{ runner.os }}-build- 39 | ${{ runner.os }}- 40 | - name: Install dependencies 41 | run: pnpm install 42 | - name: Build 43 | run: pnpm run -r build 44 | - name: lint & test 45 | run: | 46 | pnpm run -r lint 47 | pnpm run -r coverage 48 | - name: submit coverage 49 | env: 50 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 51 | run: pnpm run coverage.submit 52 | -------------------------------------------------------------------------------- /packages/sql/src/lib/sequelize.ts: -------------------------------------------------------------------------------- 1 | import { Condition } from '@ucast/core'; 2 | import { ModelStatic, Utils, literal } from 'sequelize'; 3 | import { 4 | createSqlInterpreter, 5 | allInterpreters, 6 | SqlOperator, 7 | createDialects, 8 | mysql 9 | } from '../index'; 10 | 11 | const hasOwn = Object.hasOwn || 12 | Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); 13 | 14 | function joinRelation(relationName: string, Model: ModelStatic) { 15 | return hasOwn(Model.associations, relationName); 16 | } 17 | 18 | const dialects = createDialects({ 19 | joinRelation, 20 | paramPlaceholder: mysql.paramPlaceholder, 21 | }); 22 | 23 | export function createInterpreter(interpreters: Record>) { 24 | const interpretSQL = createSqlInterpreter(interpreters); 25 | 26 | return (condition: Condition, Model: ModelStatic) => { 27 | const dialect = Model.sequelize!.getDialect() as keyof typeof dialects; 28 | const options = dialects[dialect]; 29 | 30 | if (!options) { 31 | throw new Error(`Unsupported database dialect: ${dialect}`); 32 | } 33 | 34 | const [sql, params, joins] = interpretSQL(condition, options, Model); 35 | return { 36 | include: joins.map(association => ({ association, required: true })), 37 | where: literal(Utils.format([sql, ...(params as string[])], dialect)), 38 | }; 39 | }; 40 | } 41 | 42 | export const interpret = createInterpreter(allInterpreters); 43 | -------------------------------------------------------------------------------- /packages/core/spec/interpreter.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai' 2 | import { FieldCondition, createInterpreter } from '../src' 3 | 4 | describe('createInterpreter', () => { 5 | let condition: FieldCondition 6 | 7 | beforeEach(() => { 8 | condition = new FieldCondition('eq', 'title', 'test') 9 | }) 10 | 11 | it('creates a function which mimics return type and parameters of operators', () => { 12 | const eq = (_: FieldCondition, _1: string, _2: {}) => false 13 | const interpret = createInterpreter({ eq }) 14 | const returnType: ReturnType = true 15 | const args: Parameters = [condition, 'test'] 16 | 17 | expect(args).to.equal(args) 18 | expect(returnType).to.equal(true) 19 | expect(interpret).to.be.a('function') 20 | }) 21 | 22 | it('throws exception if trying to interpret unknown operator', () => { 23 | const lt = (_: FieldCondition, _1: string, _2: {}) => false 24 | const interpret = createInterpreter({ lt }) 25 | expect(() => interpret(condition, 'test')).to.throw(/Unable to interpret/) 26 | }) 27 | 28 | it('passes options passed in "interpret" function and this function itself in operator interpreter as the last argument', () => { 29 | const eq = (_: FieldCondition, _1: string, context: any) => context 30 | const options = { a: 1, b: 2, c: Symbol('test') } 31 | const interpret = createInterpreter({ eq }, options) 32 | const context = interpret(condition, 'test') 33 | 34 | expect(context).to.deep.equal({ ...options, interpret }) 35 | }) 36 | }) 37 | -------------------------------------------------------------------------------- /packages/js/spec/fieldConditionInterpreter.behavior.ts: -------------------------------------------------------------------------------- 1 | import { FieldCondition as Field } from '@ucast/core' 2 | import { expect, spy } from './specHelper' 3 | import { createJsInterpreter, allInterpreters, compare as defaultCompare } from '../src' 4 | 5 | type Operators = keyof typeof allInterpreters 6 | 7 | export function includeExamplesForFieldCondition(name: Operators, defaultValue: unknown = 1) { 8 | const operators = { [name]: allInterpreters[name] } 9 | 10 | it('uses "get" function from context to retrieve object value', () => { 11 | const condition = new Field(name, 'value', defaultValue) 12 | const object = { value: condition.value } 13 | const get = spy((item: Record, field: string) => item[field]) 14 | const customInterpret = createJsInterpreter(operators, { get }) 15 | customInterpret(condition, object) 16 | 17 | expect(get).to.have.been.called.with(object, condition.field) 18 | }) 19 | } 20 | 21 | export function includeExamplesForEqualityInterpreter(name: Operators, defaultValue: unknown = []) { 22 | const operators = { [name]: allInterpreters[name] } 23 | 24 | it('uses "compare" function from context to check equality of values', () => { 25 | const condition = new Field(name, 'value', defaultValue) 26 | const compare = spy(defaultCompare) 27 | const object = { value: condition.value } 28 | const interpret = createJsInterpreter(operators, { compare }) 29 | interpret(condition, object) 30 | 31 | expect(compare).to.have.been.called.with(condition.value, object.value) 32 | }) 33 | } 34 | -------------------------------------------------------------------------------- /packages/core/src/Condition.ts: -------------------------------------------------------------------------------- 1 | export interface Note { 2 | type: string 3 | message?: string 4 | originalValue?: T 5 | } 6 | 7 | export abstract class Condition { 8 | private _notes!: Note[]; 9 | 10 | constructor( 11 | public readonly operator: string, 12 | public readonly value: T 13 | ) { 14 | Object.defineProperty(this, '_notes', { 15 | writable: true 16 | }); 17 | } 18 | 19 | get notes(): readonly Note[] | undefined { 20 | return this._notes; 21 | } 22 | 23 | addNote(note: Note) { 24 | this._notes = this._notes || []; 25 | this._notes.push(note); 26 | } 27 | } 28 | 29 | export class DocumentCondition extends Condition { 30 | } 31 | 32 | export class CompoundCondition extends DocumentCondition { 33 | constructor(operator: string, conditions: T[]) { 34 | if (!Array.isArray(conditions)) { 35 | throw new Error(`"${operator}" operator expects to receive an array of conditions`); 36 | } 37 | 38 | super(operator, conditions); 39 | } 40 | } 41 | 42 | export const ITSELF = '__itself__'; 43 | export class FieldCondition extends Condition { 44 | public readonly field!: string | typeof ITSELF; 45 | 46 | constructor(operator: string, field: string | typeof ITSELF, value: T) { 47 | super(operator, value); 48 | this.field = field; 49 | } 50 | } 51 | 52 | export const NULL_CONDITION = new DocumentCondition('__null__', null); 53 | export type ConditionValue = T extends Condition ? V : unknown; 54 | -------------------------------------------------------------------------------- /packages/mongo2js/spec/squire.spec.ts: -------------------------------------------------------------------------------- 1 | import { squire } from '../src' 2 | import { expect } from './specHelper' 3 | 4 | describe('squire', () => { 5 | it('creates a mongo query matcher for primitives', () => { 6 | const test = squire({ $lt: 1 }) 7 | 8 | expect(test(2)).to.be.false 9 | expect(test(0)).to.be.true 10 | }) 11 | 12 | it('accepts generic parameter type', () => { 13 | const test = squire({ $eq: 'test' }) 14 | 15 | expect(test('test')).to.be.true 16 | expect(test('test2')).to.be.false 17 | }) 18 | 19 | it('can compare Dates', () => { 20 | const now = new Date() 21 | const test = squire({ $gt: now }) 22 | 23 | expect(test(new Date(now.getTime() + 10))).to.be.true 24 | expect(test(now.getTime() + 10)).to.be.true 25 | expect(test(now.getTime() - 10)).to.be.false 26 | }) 27 | 28 | it('can interpret `$and` operator for primitives', () => { 29 | const test = squire({ $and: [{ $gt: 5 }, { $lt: 10 }] }) 30 | 31 | expect(test(6)).to.be.true 32 | expect(test(3)).to.be.false 33 | }) 34 | 35 | it('can interpret `$or` operator for primitives', () => { 36 | const test = squire({ $or: [{ $gt: 6 }, { $eq: 6 }] }) 37 | 38 | expect(test(6)).to.be.true 39 | expect(test(7)).to.be.true 40 | expect(test(3)).to.be.false 41 | }) 42 | 43 | it('can interpret `$nor` operator for primitives', () => { 44 | const test = squire({ $nor: [{ $gt: 6 }, { $eq: 6 }] }) 45 | 46 | expect(test(6)).to.be.false 47 | expect(test(7)).to.be.false 48 | expect(test(3)).to.be.true 49 | }) 50 | }) 51 | -------------------------------------------------------------------------------- /packages/sql/src/lib/mikro-orm.ts: -------------------------------------------------------------------------------- 1 | import { Condition } from '@ucast/core'; 2 | import { QueryBuilder, AnyEntity, EntityMetadata } from 'mikro-orm'; 3 | import { 4 | createSqlInterpreter, 5 | allInterpreters, 6 | SqlOperator, 7 | createDialects, 8 | mysql 9 | } from '../index'; 10 | 11 | function joinRelation>(relationName: string, query: QueryBuilder) { 12 | const privateQuery = query as any; 13 | const meta = privateQuery.metadata.get(privateQuery.entityName) as EntityMetadata; 14 | const prop = meta.properties[relationName as keyof T & string]; 15 | 16 | if (prop && prop.reference) { 17 | query.join(`${query.alias}.${relationName}`, relationName); 18 | return true; 19 | } 20 | 21 | return false; 22 | } 23 | 24 | const dialects = createDialects({ 25 | joinRelation, 26 | paramPlaceholder: mysql.paramPlaceholder, 27 | }); 28 | 29 | export function createInterpreter(interpreters: Record>) { 30 | const interpretSQL = createSqlInterpreter(interpreters); 31 | 32 | return >(condition: Condition, query: QueryBuilder) => { 33 | const dialect = (query as any).driver.config.get('type') as keyof typeof dialects; 34 | const options = dialects[dialect]; 35 | 36 | if (!options) { 37 | throw new Error(`Unsupported database dialect: ${dialect}`); 38 | } 39 | 40 | const [sql, params] = interpretSQL(condition, options, query); 41 | return query.where(sql, params); 42 | }; 43 | } 44 | 45 | export const interpret = createInterpreter(allInterpreters); 46 | -------------------------------------------------------------------------------- /semantic-release.js: -------------------------------------------------------------------------------- 1 | const parser = require('git-log-parser'); // eslint-disable-line 2 | 3 | // this is hack which allows to use semantic-release for monorepo 4 | // https://github.com/semantic-release/semantic-release/issues/193#issuecomment-578436666 5 | parser.parse = (parse => (config, options) => { 6 | if (Array.isArray(config._)) { 7 | config._.push(options.cwd); 8 | } else if (config._) { 9 | config._ = [config._, options.cwd]; 10 | } else { 11 | config._ = options.cwd; 12 | } 13 | return parse(config, options); 14 | })(parser.parse); 15 | 16 | module.exports = { 17 | tagFormat: `${process.env.npm_package_name}@\${version}`, 18 | branches: [ 19 | 'master', 20 | { name: 'next', channel: 'next', prerelease: true }, 21 | { name: 'alpha', channel: 'alpha', prerelease: true }, 22 | ], 23 | plugins: [ 24 | ['@semantic-release/commit-analyzer', { 25 | releaseRules: [ 26 | { type: 'chore', scope: 'deps', release: 'patch' }, 27 | { type: 'docs', scope: 'README', release: 'patch' }, 28 | ] 29 | }], 30 | '@semantic-release/release-notes-generator', 31 | ['@semantic-release/changelog', { 32 | changelogTitle: '# Change Log\n\nAll notable changes to this project will be documented in this file.' 33 | }], 34 | '@semantic-release/npm', 35 | ['@semantic-release/git', { 36 | message: `chore(release): ${process.env.npm_package_name}@\${nextRelease.version} [skip ci]` 37 | }], 38 | ["@semantic-release/github", { 39 | releasedLabels: false, 40 | successComment: false, 41 | }] 42 | ], 43 | }; 44 | -------------------------------------------------------------------------------- /packages/sql/src/lib/typeorm.ts: -------------------------------------------------------------------------------- 1 | import { Condition } from '@ucast/core'; 2 | import { ObjectLiteral, SelectQueryBuilder } from 'typeorm'; 3 | import { 4 | createSqlInterpreter, 5 | allInterpreters, 6 | SqlOperator, 7 | createDialects 8 | } from '../index'; 9 | 10 | function joinRelation( 11 | relationName: string, 12 | query: SelectQueryBuilder, 13 | ) { 14 | const meta = query.expressionMap.mainAlias!.metadata; 15 | const relation = meta.findRelationWithPropertyPath(relationName); 16 | 17 | if (relation) { 18 | query.innerJoin(`${query.alias}.${relationName}`, relationName); 19 | return true; 20 | } 21 | 22 | return false; 23 | } 24 | 25 | const typeormPlaceholder = (index: number) => `:${index - 1}`; 26 | 27 | const dialects = createDialects({ 28 | joinRelation, 29 | paramPlaceholder: typeormPlaceholder, 30 | }); 31 | 32 | 33 | dialects.sqlite.escapeField = dialects.sqlite3.escapeField = dialects.pg.escapeField; 34 | 35 | export function createInterpreter(interpreters: Record>) { 36 | const interpretSQL = createSqlInterpreter(interpreters); 37 | 38 | return ( 39 | condition: Condition, 40 | query: SelectQueryBuilder, 41 | ) => { 42 | const dialect = query.connection.options.type as keyof typeof dialects; 43 | const options = dialects[dialect]; 44 | 45 | if (!options) { 46 | throw new Error(`Unsupported database dialect: ${dialect}`); 47 | } 48 | 49 | const [sql, params] = interpretSQL(condition, options, query); 50 | return query.where(sql, params); 51 | }; 52 | } 53 | 54 | export const interpret = createInterpreter(allInterpreters); 55 | -------------------------------------------------------------------------------- /packages/js/src/interpreter.ts: -------------------------------------------------------------------------------- 1 | import { createInterpreter, ITSELF } from '@ucast/core'; 2 | import { getValueByPath, AnyObject, GetField } from './utils'; 3 | import { JsInterpretationOptions, JsInterpreter } from './types'; 4 | 5 | const defaultGet = (object: AnyObject, field: string) => object[field]; 6 | type Field = string | typeof ITSELF; 7 | 8 | export function getObjectFieldCursor(object: T, path: string, get: GetField) { 9 | const dotIndex = path.lastIndexOf('.'); 10 | 11 | if (dotIndex === -1) { 12 | return [object, path] as const; 13 | } 14 | 15 | return [ 16 | get(object, path.slice(0, dotIndex)) as T, 17 | path.slice(dotIndex + 1) 18 | ] as const; 19 | } 20 | 21 | export function getObjectField(object: unknown, field: Field, get: GetField = defaultGet) { 22 | if (field === ITSELF) { 23 | return object; 24 | } 25 | 26 | if (!object) { 27 | throw new Error(`Unable to get field "${field}" out of ${String(object)}.`); 28 | } 29 | 30 | return getValueByPath(object as Record, field, get); 31 | } 32 | 33 | export function createGetter(get: T) { 34 | return (object: Parameters[0], field: Parameters[1]) => getObjectField(object, field, get); 35 | } 36 | 37 | export function compare(a: T, b: T): 0 | 1 | -1 { 38 | if (a === b) { 39 | return 0; 40 | } 41 | 42 | return a > b ? 1 : -1; 43 | } 44 | 45 | export function createJsInterpreter< 46 | T extends JsInterpreter, 47 | O extends Partial 48 | >( 49 | operators: Record, 50 | options: O = {} as O 51 | ) { 52 | return createInterpreter(operators, { 53 | get: getObjectField, 54 | compare, 55 | ...options, 56 | }); 57 | } 58 | -------------------------------------------------------------------------------- /packages/sql/spec/sequelize.spec.ts: -------------------------------------------------------------------------------- 1 | import { FieldCondition } from '@ucast/core' 2 | import { Model, Sequelize, DataTypes } from 'sequelize' 3 | import { interpret } from '../src/lib/sequelize' 4 | import { expect } from './specHelper' 5 | 6 | describe('Condition interpreter for Sequelize', () => { 7 | const { User } = configureORM() 8 | 9 | it('returns an object with `where` and `include` keys', () => { 10 | const condition = new FieldCondition('eq', 'name', 'test') 11 | const query = interpret(condition, User) 12 | 13 | expect(query).to.be.an('object') 14 | expect(query.where.val).to.equal('`name` = \'test\'') 15 | expect(query.include).to.be.an('array').that.is.empty 16 | }) 17 | 18 | it('properly binds parameters for "IN" operator', () => { 19 | const condition = new FieldCondition('in', 'age', [1, 2, 3]) 20 | const query = interpret(condition, User) 21 | 22 | expect(query.where.val).to.equal('`age` in(1, 2, 3)') 23 | }) 24 | 25 | it('automatically inner joins relation when condition is set on relation field', () => { 26 | const condition = new FieldCondition('eq', 'projects.name', 'test') 27 | const query = interpret(condition, User) 28 | 29 | expect(query.include).to.deep.equal([ 30 | { association: 'projects', required: true } 31 | ]) 32 | expect(query.where.val).to.equal('`projects`.`name` = \'test\'') 33 | }) 34 | }) 35 | 36 | function configureORM() { 37 | const sequelize = new Sequelize('sqlite::memory:') 38 | 39 | class User extends Model {} 40 | class Project extends Model {} 41 | 42 | User.init({ 43 | name: { type: DataTypes.STRING }, 44 | email: { type: DataTypes.STRING }, 45 | }, { sequelize, modelName: 'user' }) 46 | 47 | Project.init({ 48 | name: { type: DataTypes.STRING }, 49 | active: { type: DataTypes.BOOLEAN } 50 | }, { sequelize, modelName: 'project' }) 51 | 52 | Project.belongsTo(User) 53 | User.hasMany(Project) 54 | 55 | return { User, Project } 56 | } 57 | -------------------------------------------------------------------------------- /packages/mongo/src/types.ts: -------------------------------------------------------------------------------- 1 | import { Comparable } from '@ucast/core'; 2 | 3 | export interface MongoQueryTopLevelOperators { 4 | $and?: MongoQuery[], 5 | $or?: MongoQuery[], 6 | $nor?: MongoQuery[], 7 | $where?: (this: Value) => boolean 8 | } 9 | 10 | export interface MongoQueryFieldOperators { 11 | $eq?: Value, 12 | $ne?: Value, 13 | $lt?: Extract, 14 | $lte?: Extract, 15 | $gt?: Extract, 16 | $gte?: Extract, 17 | $in?: Value[], 18 | $nin?: Value[], 19 | $all?: Value[], 20 | /** checks by array length */ 21 | $size?: number, 22 | $regex?: RegExp | string, 23 | $options?: 'i' | 'g' | 'm' | 'u', 24 | /** checks the shape of array item */ 25 | $elemMatch?: MongoQuery, 26 | $exists?: boolean, 27 | $not?: Omit, '$not'>, 28 | } 29 | 30 | export type MongoQueryOperators = 31 | MongoQueryFieldOperators & MongoQueryTopLevelOperators; 32 | 33 | export interface CustomOperators { 34 | toplevel?: {} 35 | field?: {} 36 | } 37 | 38 | type ItemOf = T extends any[] 39 | ? T[number] | AdditionalArrayTypes 40 | : T; 41 | type OperatorValues = null | T | Partial> | MongoQueryFieldOperators>; 42 | type Query, FieldOperators> = { 43 | [K in keyof T]?: OperatorValues | FieldOperators 44 | }; 45 | 46 | export interface DefaultOperators { 47 | toplevel: MongoQueryTopLevelOperators 48 | field: MongoQueryOperators 49 | } 50 | 51 | export type BuildMongoQuery< 52 | T = Record, 53 | O extends CustomOperators = DefaultOperators 54 | > = T extends Record 55 | ? Query & O['toplevel'] 56 | : O['field'] & O['toplevel']; 57 | 58 | export type MongoQuery, O extends CustomOperators = CustomOperators> = 59 | BuildMongoQuery & O>; 60 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | .vscode 106 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ucast", 3 | "version": "0.0.1", 4 | "private": true, 5 | "description": "git@github.com:stalniy/ucast.git", 6 | "lint-staged": { 7 | "**/*.{js,ts}": [ 8 | "eslint --fix --ext .js,.ts" 9 | ] 10 | }, 11 | "scripts": { 12 | "coverage.submit": "codecov --disable=gcov", 13 | "prepare": "husky" 14 | }, 15 | "repository": { 16 | "type": "git", 17 | "url": "git+https://github.com/stalniy/ucast.git" 18 | }, 19 | "keywords": [ 20 | "where", 21 | "sql", 22 | "mongo", 23 | "conditions", 24 | "query", 25 | "builder", 26 | "ast" 27 | ], 28 | "author": "Sergii Stotskyi ", 29 | "license": "Apache-2.0", 30 | "bugs": { 31 | "url": "https://github.com/stalniy/ucast/issues" 32 | }, 33 | "homepage": "https://github.com/stalniy/ucast#readme", 34 | "devDependencies": { 35 | "@babel/core": "^7.10.2", 36 | "@babel/plugin-proposal-class-properties": "^7.10.4", 37 | "@babel/plugin-proposal-object-rest-spread": "^7.10.1", 38 | "@babel/plugin-transform-typescript": "^7.10.1", 39 | "@babel/preset-env": "^7.10.2", 40 | "@eslint/js": "^9.34.0", 41 | "@rollup/plugin-babel": "^5.0.3", 42 | "@rollup/plugin-commonjs": "^14.0.0", 43 | "@rollup/plugin-node-resolve": "^8.0.1", 44 | "@semantic-release/changelog": "^5.0.1", 45 | "@semantic-release/git": "^9.0.0", 46 | "@semantic-release/github": "^7.0.7", 47 | "@semantic-release/npm": "^7.0.5", 48 | "@stylistic/eslint-plugin-js": "^4.4.1", 49 | "@stylistic/eslint-plugin-ts": "^4.4.1", 50 | "@types/chai": "^4.2.11", 51 | "@types/chai-spies": "^1.0.1", 52 | "@types/mocha": "^7.0.2", 53 | "chai": "^4.2.0", 54 | "chai-spies": "^1.0.0", 55 | "codecov": "^3.7.0", 56 | "eslint-plugin-import": "^2.32.0", 57 | "globals": "^16.3.0", 58 | "husky": "^9.1.7", 59 | "lint-staged": "^15.4.3", 60 | "mocha": "^8.0.1", 61 | "nyc": "^15.1.0", 62 | "rollup": "^2.15.0", 63 | "rollup-plugin-terser": "^6.1.0", 64 | "semantic-release": "^17.4.7", 65 | "ts-node": "^8.10.2", 66 | "typescript": "^5.9.2", 67 | "typescript-eslint": "^8.42.0" 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /packages/js/src/utils.ts: -------------------------------------------------------------------------------- 1 | import { FieldCondition } from '@ucast/core'; 2 | import { JsInterpretationOptions, JsInterpreter } from './types'; 3 | 4 | export type AnyObject = Record; 5 | export type GetField = (object: any, field: string) => any; 6 | 7 | export function includes( 8 | items: T[], 9 | value: T, 10 | compare: JsInterpretationOptions['compare'] 11 | ): boolean { 12 | for (let i = 0, length = items.length; i < length; i++) { 13 | if (compare(items[i], value) === 0) { 14 | return true; 15 | } 16 | } 17 | 18 | return false; 19 | } 20 | 21 | export function isArrayAndNotNumericField(object: T | T[], field: string): object is T[] { 22 | return Array.isArray(object) && Number.isNaN(Number(field)); 23 | } 24 | 25 | function getField(object: T | T[], field: string, get: GetField) { 26 | if (!isArrayAndNotNumericField(object, field)) { 27 | return get(object, field); 28 | } 29 | 30 | let result: unknown[] = []; 31 | 32 | for (let i = 0; i < object.length; i++) { 33 | const value = get(object[i], field); 34 | if (typeof value !== 'undefined') { 35 | result = result.concat(value); 36 | } 37 | } 38 | 39 | return result; 40 | } 41 | 42 | export function getValueByPath(object: AnyObject, field: string, get: GetField) { 43 | if (field.indexOf('.') === -1) { 44 | return getField(object, field, get); 45 | } 46 | 47 | const paths = field.split('.'); 48 | let value = object; 49 | 50 | for (let i = 0, length = paths.length; i < length; i++) { 51 | value = getField(value, paths[i], get); 52 | 53 | if (!value || typeof value !== 'object') { 54 | return value; 55 | } 56 | } 57 | 58 | return value; 59 | } 60 | 61 | export function testValueOrArray(test: JsInterpreter, U>) { 62 | return ((node, object, context) => { 63 | const value = context.get(object, node.field); 64 | 65 | if (!Array.isArray(value)) { 66 | return test(node, value, context); 67 | } 68 | 69 | return value.some(v => test(node, v, context)); 70 | }) as JsInterpreter, AnyObject | U>; 71 | } 72 | 73 | export const hasOwn = Object.hasOwn || 74 | Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); 75 | -------------------------------------------------------------------------------- /packages/js/spec/getObjectField.spec.ts: -------------------------------------------------------------------------------- 1 | import { ITSELF } from '@ucast/core' 2 | import { expect } from './specHelper' 3 | import { getObjectField } from '../src' 4 | 5 | describe('getObjectField', () => { 6 | it('returns passed value if field equals to ITSELF constant', () => { 7 | const object = {} 8 | expect(getObjectField(object, ITSELF)).to.equal(object) 9 | }) 10 | 11 | it('returns specified object field value', () => { 12 | const object = { age: 1 } 13 | expect(getObjectField(object, 'age')).to.equal(object.age) 14 | }) 15 | 16 | it('returns specified array item field values', () => { 17 | const object = [{ age: 1 }, { age: 2 }] 18 | expect(getObjectField(object, 'age')).to.deep.equal([1, 2]) 19 | }) 20 | 21 | it('returns nested property value specified by dot notation (e.g., "address.street")', () => { 22 | const object = { address: { street: 'test' } } 23 | expect(getObjectField(object, 'address.street')).to.equal(object.address.street) 24 | }) 25 | 26 | it('returns nested property values from array', () => { 27 | const object = { items: [{ price: 12 }, { price: 14 }] } 28 | expect(getObjectField(object, 'items.price')).to.deep.equal([12, 14]) 29 | }) 30 | 31 | it('returns property values from nested array as flat array', () => { 32 | const object = { items: [{ specs: [{ price: 12 }] }, { specs: [{ price: 14 }] }] } 33 | expect(getObjectField(object, 'items.specs.price')).to.deep.equal([12, 14]) 34 | }) 35 | 36 | it('returns array item when specified number as the last path field', () => { 37 | const object = { items: [{ price: 12 }, { price: 14 }] } 38 | expect(getObjectField(object, 'items.0')).to.deep.equal({ price: 12 }) 39 | }) 40 | 41 | it('throws exception when trying to get property of not an object', () => { 42 | expect(() => getObjectField(null, 'item')).to.throw(/Unable to get field/) 43 | expect(() => getObjectField(undefined, 'item')).to.throw(/Unable to get field/) 44 | }) 45 | 46 | it('allows to pass custom "get" function', () => { 47 | const state: Record = { value: 1, age: 10 } 48 | const object = { get: (field: string) => state[field] } 49 | const get = (item: typeof object, field: string) => item.get(field) 50 | 51 | expect(getObjectField(object, 'value', get)).to.equal(state.value) 52 | }) 53 | }) 54 | -------------------------------------------------------------------------------- /packages/sql/src/dialects.ts: -------------------------------------------------------------------------------- 1 | function posixRegex(field: string, placeholder: string, ignoreCase: boolean) { 2 | const operator = ignoreCase ? '~*' : '~'; 3 | return `${field} ${operator} ${placeholder}`; 4 | } 5 | 6 | function regexp(field: string, placeholder: string) { 7 | return `${field} regexp ${placeholder} = 1`; 8 | } 9 | 10 | const questionPlaceholder = () => '?'; 11 | const $indexPlaceholder = (index: number) => `$${index}`; 12 | 13 | export const oracle = { 14 | regexp: posixRegex, 15 | paramPlaceholder: $indexPlaceholder, 16 | escapeField: (field: string) => `"${field}"`, 17 | }; 18 | export const pg = oracle; 19 | 20 | export const mysql = { 21 | regexp, 22 | paramPlaceholder: questionPlaceholder, 23 | escapeField: (field: string) => `\`${field}\``, 24 | }; 25 | export const sqlite = mysql; 26 | 27 | export const mssql = { 28 | regexp() { 29 | throw new Error('"regexp" operator is not supported in MSSQL'); 30 | }, 31 | paramPlaceholder: questionPlaceholder, 32 | escapeField: (field: string) => `[${field}]`, 33 | }; 34 | 35 | export interface DialectOptions { 36 | regexp(field: string, placeholder: string, ignoreCase: boolean): string 37 | joinRelation?(relationName: string, context: unknown): boolean 38 | escapeField(field: string): string 39 | paramPlaceholder(index: number): string 40 | } 41 | 42 | export type SupportedDialects = 'mssql' | 43 | 'postgres' | 44 | 'pg' | 45 | 'oracle' | 46 | 'oracledb' | 47 | 'mysql' | 48 | 'mysql2' | 49 | 'mariadb' | 50 | 'sqlite3' | 51 | 'sqlite'; 52 | type Dialects = Record; 53 | 54 | export function createDialects>(options: T): Dialects { 55 | const mssqlOptions = { 56 | ...mssql, 57 | ...options, 58 | }; 59 | const pgOptions = { 60 | ...pg, 61 | ...options, 62 | }; 63 | const oracleOptions = { 64 | ...oracle, 65 | ...options, 66 | }; 67 | const mysqlOptions = { 68 | ...mysql, 69 | ...options, 70 | }; 71 | const sqliteOptions = { 72 | ...sqlite, 73 | ...options, 74 | }; 75 | 76 | return { 77 | mssql: mssqlOptions, 78 | oracle: oracleOptions, 79 | oracledb: oracleOptions, 80 | pg: pgOptions, 81 | postgres: pgOptions, 82 | mysql: mysqlOptions, 83 | mysql2: mysqlOptions, 84 | mariadb: mysqlOptions, 85 | sqlite: sqliteOptions, 86 | sqlite3: sqliteOptions, 87 | }; 88 | } 89 | -------------------------------------------------------------------------------- /packages/core/src/utils.ts: -------------------------------------------------------------------------------- 1 | import { Condition, CompoundCondition, NULL_CONDITION } from './Condition'; 2 | 3 | const hasOwn = Object.hasOwn || 4 | Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); 5 | 6 | export function isCompound(operator: string, condition: Condition): condition is CompoundCondition { 7 | return condition instanceof CompoundCondition && condition.operator === operator; 8 | } 9 | 10 | function flattenConditions( 11 | operator: string, 12 | conditions: T[], 13 | aggregatedResult?: T[] 14 | ) { 15 | const flatConditions: T[] = aggregatedResult || []; 16 | 17 | for (let i = 0, length = conditions.length; i < length; i++) { 18 | const currentNode = conditions[i]; 19 | 20 | if (isCompound(operator, currentNode)) { 21 | flattenConditions(operator, currentNode.value as T[], flatConditions); 22 | } else { 23 | flatConditions.push(currentNode); 24 | } 25 | } 26 | 27 | return flatConditions; 28 | } 29 | 30 | export function optimizedCompoundCondition(operator: string, conditions: T[]) { 31 | if (conditions.length === 1) { 32 | return conditions[0]; 33 | } 34 | 35 | return new CompoundCondition(operator, flattenConditions(operator, conditions)); 36 | } 37 | 38 | export const identity = (x: T) => x; 39 | export const object = () => Object.create(null); 40 | 41 | export const ignoreValue: IgnoreValue = Object.defineProperty(object(), '__@type@__', { 42 | value: 'ignore value' 43 | }); 44 | export interface IgnoreValue { 45 | readonly ['__@type@__']: 'ignore value' 46 | } 47 | 48 | export function hasOperators( 49 | value: any, 50 | instructions: Record, 51 | skipIgnore = false, 52 | ): value is T { 53 | if (!value || value && value.constructor !== Object) { 54 | return false; 55 | } 56 | 57 | for (const prop in value) { 58 | const hasProp = hasOwn(value, prop) && hasOwn(instructions, prop); 59 | if (hasProp && (!skipIgnore || value[prop] !== ignoreValue)) { 60 | return true; 61 | } 62 | } 63 | 64 | return false; 65 | } 66 | 67 | export function objectKeysSkipIgnore(anyObject: Record) { 68 | const keys: string[] = []; 69 | for (const key in anyObject) { 70 | if (hasOwn(anyObject, key) && anyObject[key] !== ignoreValue) { 71 | keys.push(key); 72 | } 73 | } 74 | 75 | return keys; 76 | } 77 | 78 | export function pushIfNonNullCondition(conditions: Condition[], condition: Condition) { 79 | if (condition !== NULL_CONDITION) { 80 | conditions.push(condition); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /packages/sql/spec/objection.spec.ts: -------------------------------------------------------------------------------- 1 | import { FieldCondition } from '@ucast/core' 2 | import { Model, QueryBuilder } from 'objection' 3 | import Knex from 'knex' 4 | import { interpret } from '../src/lib/objection' 5 | import { expect, linearize } from './specHelper' 6 | 7 | describe('Condition interpreter for Objection', () => { 8 | const { User } = configureORM() 9 | 10 | it('returns `QueryBuilder`', () => { 11 | const condition = new FieldCondition('eq', 'name', 'test') 12 | const query = interpret(condition, User.query()) 13 | 14 | expect(query).to.be.instanceOf(QueryBuilder) 15 | }) 16 | 17 | it('properly binds parameters', () => { 18 | const condition = new FieldCondition('eq', 'name', 'test') 19 | const query = interpret(condition, User.query()) 20 | 21 | expect(query.toKnexQuery().toString()).to.equal(` 22 | select "users".* from "users" where "name" = 'test' 23 | `.trim()) 24 | }) 25 | 26 | it('properly binds parameters for "IN" operator', () => { 27 | const condition = new FieldCondition('in', 'age', [1, 2, 3]) 28 | const query = interpret(condition, User.query()) 29 | 30 | expect(query.toKnexQuery().toString()).to.equal(` 31 | select "users".* from "users" where "age" in(1, 2, 3) 32 | `.trim()) 33 | }) 34 | 35 | it('automatically inner joins relation when condition is set on relation field', () => { 36 | const condition = new FieldCondition('eq', 'projects.name', 'test') 37 | const query = interpret(condition, User.query()) 38 | 39 | expect(query.toKnexQuery().toString()).to.equal(linearize` 40 | select "users".* 41 | from "users" 42 | inner join "projects" on "projects"."user_id" = "users"."id" 43 | where "projects"."name" = 'test' 44 | `.trim()) 45 | }) 46 | }) 47 | 48 | function configureORM() { 49 | Model.knex(Knex({ client: 'pg' })) 50 | 51 | class User extends Model { 52 | static tableName = 'users' 53 | 54 | static get relationMappings() { 55 | return { 56 | projects: { 57 | relation: Model.HasManyRelation, 58 | modelClass: Project, 59 | join: { from: 'users.id', to: 'projects.user_id' } 60 | } 61 | } 62 | } 63 | } 64 | 65 | class Project extends Model { 66 | static tableName = 'projects' 67 | 68 | static get relationMappings() { 69 | return { 70 | user: { 71 | relation: Model.BelongsToOneRelation, 72 | modelClass: User, 73 | join: { from: 'users.id', to: 'projects.user_id' } 74 | } 75 | } 76 | } 77 | } 78 | 79 | return { User, Project } 80 | } 81 | -------------------------------------------------------------------------------- /packages/js/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ucast/js", 3 | "version": "3.0.4", 4 | "description": "git@github.com:stalniy/ucast.git", 5 | "sideEffects": false, 6 | "main": "dist/es6c/index.js", 7 | "module": "dist/es5m/index.js", 8 | "es2015": "dist/es6m/index.mjs", 9 | "legacy": "dist/umd/index.js", 10 | "typings": "dist/types/index.d.ts", 11 | "exports": { 12 | ".": { 13 | "types": "./dist/types/index.d.ts", 14 | "import": "./dist/es6m/index.mjs", 15 | "require": "./dist/es6c/index.js" 16 | } 17 | }, 18 | "scripts": { 19 | "build.types": "tsc", 20 | "prebuild": "rm -rf dist/* && npm run build.types", 21 | "build": "rollup -c ../../rollup.config.js -n ucast.js -g @ucast/core:ucast.core", 22 | "lint": "eslint --ext .js,.ts src/ spec/", 23 | "test": "mocha -r ts-node/register spec/*", 24 | "coverage": "nyc -n src npm run test && nyc report --reporter=lcov", 25 | "prerelease": "npm run lint && npm test && NODE_ENV=production npm run build", 26 | "release": "semantic-release -e ../../semantic-release.js" 27 | }, 28 | "publishConfig": { 29 | "access": "public" 30 | }, 31 | "files": [ 32 | "dist", 33 | "NOTICE", 34 | "*.d.ts" 35 | ], 36 | "repository": { 37 | "type": "git", 38 | "url": "git+https://github.com/stalniy/ucast.git" 39 | }, 40 | "keywords": [ 41 | "ast", 42 | "interpreter", 43 | "conditions", 44 | "query", 45 | "builder" 46 | ], 47 | "author": "Sergii Stotskyi ", 48 | "license": "Apache-2.0", 49 | "bugs": { 50 | "url": "https://github.com/stalniy/ucast/issues" 51 | }, 52 | "homepage": "https://github.com/stalniy/ucast#readme", 53 | "devDependencies": { 54 | "@babel/core": "^7.10.2", 55 | "@babel/plugin-proposal-class-properties": "^7.10.4", 56 | "@babel/plugin-proposal-object-rest-spread": "^7.10.4", 57 | "@babel/plugin-transform-typescript": "^7.10.1", 58 | "@babel/preset-env": "^7.10.2", 59 | "@rollup/plugin-babel": "^5.0.3", 60 | "@rollup/plugin-commonjs": "^14.0.0", 61 | "@rollup/plugin-node-resolve": "^8.0.1", 62 | "@semantic-release/changelog": "^5.0.1", 63 | "@semantic-release/git": "^9.0.0", 64 | "@semantic-release/github": "^7.0.7", 65 | "@semantic-release/npm": "^7.0.5", 66 | "@types/chai": "^4.2.11", 67 | "@types/chai-spies": "^1.0.1", 68 | "@types/mocha": "^7.0.2", 69 | "chai": "^4.2.0", 70 | "chai-spies": "^1.0.0", 71 | "mocha": "^8.0.1", 72 | "nyc": "^15.1.0", 73 | "rollup": "^2.15.0", 74 | "rollup-plugin-terser": "^6.1.0", 75 | "semantic-release": "^17.4.7", 76 | "ts-node": "^10.9.2", 77 | "typescript": "^5.9.2" 78 | }, 79 | "dependencies": { 80 | "@ucast/core": "workspace:*" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /packages/mongo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ucast/mongo", 3 | "version": "2.4.3", 4 | "description": "git@github.com:stalniy/ucast.git", 5 | "sideEffects": false, 6 | "main": "dist/es6c/index.js", 7 | "module": "dist/es5m/index.js", 8 | "es2015": "dist/es6m/index.mjs", 9 | "legacy": "dist/umd/index.js", 10 | "typings": "dist/types/index.d.ts", 11 | "exports": { 12 | ".": { 13 | "types": "./dist/types/index.d.ts", 14 | "import": "./dist/es6m/index.mjs", 15 | "require": "./dist/es6c/index.js" 16 | } 17 | }, 18 | "scripts": { 19 | "build.types": "tsc", 20 | "prebuild": "rm -rf dist/* && npm run build.types", 21 | "build": "rollup -c ../../rollup.config.js -n ucast.mongo -g @ucast/core:ucast.core", 22 | "lint": "eslint --ext .js,.ts src/ spec/", 23 | "test": "mocha -r ts-node/register spec/*", 24 | "coverage": "nyc -n src npm run test && nyc report --reporter=lcov", 25 | "prerelease": "npm run lint && npm test && NODE_ENV=production npm run build", 26 | "release": "semantic-release -e ../../semantic-release.js" 27 | }, 28 | "publishConfig": { 29 | "access": "public" 30 | }, 31 | "files": [ 32 | "dist", 33 | "NOTICE", 34 | "*.d.ts" 35 | ], 36 | "repository": { 37 | "type": "git", 38 | "url": "git+https://github.com/stalniy/ucast.git" 39 | }, 40 | "keywords": [ 41 | "mongo", 42 | "conditions", 43 | "query", 44 | "builder", 45 | "ast" 46 | ], 47 | "author": "Sergii Stotskyi ", 48 | "license": "Apache-2.0", 49 | "bugs": { 50 | "url": "https://github.com/stalniy/ucast/issues" 51 | }, 52 | "homepage": "https://github.com/stalniy/ucast#readme", 53 | "devDependencies": { 54 | "@babel/core": "^7.10.2", 55 | "@babel/plugin-proposal-class-properties": "^7.10.4", 56 | "@babel/plugin-proposal-object-rest-spread": "^7.10.4", 57 | "@babel/plugin-transform-typescript": "^7.10.1", 58 | "@babel/preset-env": "^7.10.2", 59 | "@rollup/plugin-babel": "^5.0.3", 60 | "@rollup/plugin-commonjs": "^14.0.0", 61 | "@rollup/plugin-node-resolve": "^8.0.1", 62 | "@semantic-release/changelog": "^5.0.1", 63 | "@semantic-release/git": "^9.0.0", 64 | "@semantic-release/github": "^7.0.7", 65 | "@semantic-release/npm": "^7.0.5", 66 | "@types/chai": "^4.2.11", 67 | "@types/chai-spies": "^1.0.1", 68 | "@types/mocha": "^7.0.2", 69 | "chai": "^4.2.0", 70 | "chai-spies": "^1.0.0", 71 | "mocha": "^8.0.1", 72 | "nyc": "^15.1.0", 73 | "rollup": "^2.15.0", 74 | "rollup-plugin-terser": "^6.1.0", 75 | "semantic-release": "^17.4.7", 76 | "ts-node": "^10.9.2", 77 | "typescript": "^5.9.2" 78 | }, 79 | "dependencies": { 80 | "@ucast/core": "workspace:*" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /packages/core/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ucast/core", 3 | "version": "1.10.2", 4 | "description": "git@github.com:stalniy/ucast.git", 5 | "sideEffects": false, 6 | "main": "dist/es6c/index.js", 7 | "module": "dist/es5m/index.js", 8 | "es2015": "dist/es6m/index.mjs", 9 | "legacy": "dist/umd/index.js", 10 | "typings": "dist/types/index.d.ts", 11 | "exports": { 12 | ".": { 13 | "types": "./dist/types/index.d.ts", 14 | "import": "./dist/es6m/index.mjs", 15 | "require": "./dist/es6c/index.js" 16 | } 17 | }, 18 | "scripts": { 19 | "build.types": "tsc", 20 | "prebuild": "rm -rf dist/* && npm run build.types", 21 | "build": "rollup -c ../../rollup.config.js -n ucast.core", 22 | "lint": "eslint --ext .js,.ts src/ spec/", 23 | "test": "mocha -r ts-node/register spec/*", 24 | "coverage": "nyc -n src npm run test && nyc report --reporter=lcov", 25 | "prerelease": "npm run lint && npm test && NODE_ENV=production npm run build", 26 | "release": "semantic-release -e ../../semantic-release.js" 27 | }, 28 | "publishConfig": { 29 | "access": "public" 30 | }, 31 | "files": [ 32 | "dist", 33 | "NOTICE", 34 | "*.d.ts" 35 | ], 36 | "repository": { 37 | "type": "git", 38 | "url": "https://github.com/stalniy/ucast.git", 39 | "directory": "packages/core" 40 | }, 41 | "keywords": [ 42 | "where", 43 | "sql", 44 | "mongo", 45 | "conditions", 46 | "query", 47 | "builder", 48 | "ast" 49 | ], 50 | "author": "Sergii Stotskyi ", 51 | "license": "Apache-2.0", 52 | "bugs": { 53 | "url": "https://github.com/stalniy/ucast/issues" 54 | }, 55 | "homepage": "https://github.com/stalniy/ucast#readme", 56 | "devDependencies": { 57 | "@babel/core": "^7.10.2", 58 | "@babel/plugin-proposal-class-properties": "^7.10.4", 59 | "@babel/plugin-proposal-object-rest-spread": "^7.10.4", 60 | "@babel/plugin-transform-typescript": "^7.10.1", 61 | "@babel/preset-env": "^7.10.2", 62 | "@rollup/plugin-babel": "^5.0.3", 63 | "@rollup/plugin-commonjs": "^14.0.0", 64 | "@rollup/plugin-node-resolve": "^8.0.1", 65 | "@semantic-release/changelog": "^5.0.1", 66 | "@semantic-release/git": "^9.0.0", 67 | "@semantic-release/github": "^7.0.7", 68 | "@semantic-release/npm": "^7.0.5", 69 | "@types/chai": "^4.2.11", 70 | "@types/chai-spies": "^1.0.1", 71 | "@types/mocha": "^7.0.2", 72 | "babel-register": "^6.26.0", 73 | "chai": "^4.2.0", 74 | "chai-spies": "^1.0.0", 75 | "mocha": "^8.0.1", 76 | "nyc": "^15.1.0", 77 | "rollup": "^2.15.0", 78 | "rollup-plugin-terser": "^6.1.0", 79 | "semantic-release": "^17.4.7", 80 | "ts-node": "^10.9.2", 81 | "typescript": "^5.9.2" 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /packages/core/README.md: -------------------------------------------------------------------------------- 1 | # Universal Conditions AST 2 | 3 | [![@ucast/core NPM version](https://badge.fury.io/js/%40ucast%2Fcore.svg)](https://badge.fury.io/js/%40ucast%2Fcore) 4 | [![](https://img.shields.io/npm/dm/%40ucast%2Fcore.svg)](https://www.npmjs.com/package/%40ucast%2Fcore) 5 | [![UCAST join the chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/stalniy-ucast/community) 6 | 7 | This package contains classes and functions that helps to create parsers, conditions AST, interpreters and translators. 8 | 9 | ## Installation 10 | 11 | ```sh 12 | npm i @ucast/core 13 | # or 14 | yarn add @ucast/core 15 | # or 16 | pnpm add @ucast/core 17 | ``` 18 | 19 | ## Getting Started 20 | 21 | ### Parser 22 | 23 | Parser is a function that translates conditions from any language into conditions AST. For example, `MongoQueryParser` parses MongoQuery into AST which then can be interpreted by `JavaScriptInterpreter` that returns a boolean value based on passed in object. 24 | 25 | ### Conditions AST 26 | 27 | Abstract Syntax Tree of any condition. **What is condition?** 28 | `x > 4` is a condition, `x === 4` is a condition as well, `{ x: { $eq: 4 } }` is a [MongoQuery](http://docs.mongodb.org/manual/reference/operator/query/) condition. 29 | 30 | There are few types of AST nodes that allow us to represent any condition: 31 | 32 | * **FieldCondition**. \ 33 | Depends on a field, operator and its value. For example, in condition `x > 4`, `x` is a field, `4` is a value and `>` is operator 34 | * **DocumentCondition**. \ 35 | Any condition that test a document (or a row) as whole (e.g., in MongoDB Query, it's `$where` operator and in SQL it's `EXISTS`). 36 | * **CompoundCondition**. \ 37 | Combines other conditions using logical operations like "and", "or", "not". 38 | 39 | ### Interpreter 40 | 41 | An interpreter is a function that interprets conditions AST in a specific way. For example, it can: 42 | 43 | * interpret conditions in JavaScript runtime to return a boolean result 44 | * or it can convert conditions into SQL `WHERE` statement 45 | * or MongoDB query, 46 | * or HTTP/REST query 47 | * or GraphQL input 48 | * or anything else you can imagine 49 | 50 | ### Translator 51 | 52 | Combines Parser and Interpreter and returns a factory function: 53 | 54 | ```js 55 | const parse = (query) => /* to conditions AST */ 56 | const interpreter = createInterpreter({ /* condition interpreters */ }); 57 | const translate = (query, ...args) => interpreter.bind(null, parse(query)); 58 | ``` 59 | 60 | ## Want to help? 61 | 62 | Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for [contributing] 63 | 64 | ## License 65 | 66 | [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 67 | 68 | [contributing]: https://github.com/stalniy/ucast/blob/master/CONTRIBUTING.md 69 | -------------------------------------------------------------------------------- /packages/mongo2js/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ucast/mongo2js", 3 | "version": "1.4.0", 4 | "description": "git@github.com:stalniy/ucast.git", 5 | "sideEffects": false, 6 | "main": "dist/es6c/index.js", 7 | "module": "dist/es5m/index.js", 8 | "es2015": "dist/es6m/index.mjs", 9 | "legacy": "dist/umd/index.js", 10 | "typings": "dist/types/index.d.ts", 11 | "exports": { 12 | ".": { 13 | "types": "./dist/types/index.d.ts", 14 | "import": "./dist/es6m/index.mjs", 15 | "require": "./dist/es6c/index.js" 16 | } 17 | }, 18 | "scripts": { 19 | "build.types": "tsc", 20 | "prebuild": "rm -rf dist/* && npm run build.types", 21 | "build": "rollup -c ../../rollup.config.js -n ucast.mongo2js -g @ucast/core:ucast.core,@ucast/js:ucast.js,@ucast/mongo:ucast.mongo", 22 | "lint": "eslint --ext .js,.ts src/", 23 | "test": "mocha -r ts-node/register spec/*", 24 | "coverage": "nyc -n src npm run test && nyc report --reporter=lcov", 25 | "prerelease": "npm run lint && npm test && NODE_ENV=production npm run build", 26 | "release": "semantic-release -e ../../semantic-release.js" 27 | }, 28 | "publishConfig": { 29 | "access": "public" 30 | }, 31 | "files": [ 32 | "dist", 33 | "NOTICE", 34 | "*.d.ts" 35 | ], 36 | "repository": { 37 | "type": "git", 38 | "url": "git+https://github.com/stalniy/ucast.git" 39 | }, 40 | "keywords": [ 41 | "mongo", 42 | "conditions", 43 | "query", 44 | "builder", 45 | "ast" 46 | ], 47 | "author": "Sergii Stotskyi ", 48 | "license": "Apache-2.0", 49 | "bugs": { 50 | "url": "https://github.com/stalniy/ucast/issues" 51 | }, 52 | "homepage": "https://github.com/stalniy/ucast/tree/master/packages/mongo2js#readme", 53 | "devDependencies": { 54 | "@babel/core": "^7.12.3", 55 | "@babel/plugin-proposal-class-properties": "^7.12.1", 56 | "@babel/plugin-proposal-object-rest-spread": "^7.12.1", 57 | "@babel/plugin-transform-typescript": "^7.12.1", 58 | "@babel/preset-env": "^7.12.1", 59 | "@rollup/plugin-babel": "^5.2.1", 60 | "@rollup/plugin-commonjs": "^14.0.0", 61 | "@rollup/plugin-node-resolve": "^8.4.0", 62 | "@semantic-release/changelog": "^5.0.1", 63 | "@semantic-release/git": "^9.0.0", 64 | "@semantic-release/github": "^7.1.1", 65 | "@semantic-release/npm": "^7.0.6", 66 | "@types/chai": "^4.2.14", 67 | "@types/chai-spies": "^1.0.2", 68 | "@types/mocha": "^7.0.2", 69 | "chai": "^4.2.0", 70 | "chai-spies": "^1.0.0", 71 | "mocha": "^8.2.0", 72 | "nyc": "^15.1.0", 73 | "rollup": "^2.33.1", 74 | "rollup-plugin-terser": "^6.1.0", 75 | "semantic-release": "^17.4.7", 76 | "ts-node": "^10.9.2", 77 | "typescript": "^5.9.2" 78 | }, 79 | "dependencies": { 80 | "@ucast/core": "workspace:*", 81 | "@ucast/js": "workspace:*", 82 | "@ucast/mongo": "workspace:*" 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /packages/mongo2js/spec/guard.spec.ts: -------------------------------------------------------------------------------- 1 | import { guard } from '../src' 2 | import { expect } from './specHelper' 3 | 4 | describe('guard', () => { 5 | it('creates a mongo query matcher', () => { 6 | const test = guard({ a: 1 }) 7 | expect(test({ a: 2 })).to.be.false 8 | }) 9 | 10 | it('accepts generic parameter type', () => { 11 | type Person = { firstName: string } 12 | const test = guard({ firstName: { $eq: 'test' } }) 13 | 14 | expect(test({ firstName: 'test' })).to.be.true 15 | }) 16 | 17 | it('can compare Dates', () => { 18 | const now = new Date() 19 | const test = guard({ createdAt: { $gt: now } }) 20 | 21 | expect(test({ createdAt: new Date(now.getTime() + 10) })).to.be.true 22 | expect(test({ createdAt: now.getTime() + 10 })).to.be.true 23 | expect(test({ createdAt: now.getTime() - 10 })).to.be.false 24 | }) 25 | 26 | it('can check equality of wrapper objects that have `toJSON` method (e.g., `ObjectId`)', () => { 27 | const id = (value: T) => ({ value, toJSON: () => value }) 28 | const test = guard({ id: id(1) }) 29 | 30 | expect(test({ id: 1 })).to.be.true 31 | expect(test({ id: id(1) })).to.be.true 32 | expect(test({ id: id(2) })).to.be.false 33 | }) 34 | 35 | it('supports bigint', () => { 36 | const test = guard({ id: { $eq: 1n } }) 37 | 38 | expect(test({ id: 1n })).to.be.true 39 | expect(test({ id: 1 })).to.be.false 40 | }) 41 | 42 | it('processes primitive values without attempting to call its `toJSON` method', () => { 43 | const test = guard({ 44 | number: 42, 45 | bigint: BigInt(42), 46 | string: 'test', 47 | boolean: true, 48 | null: null, 49 | undefined 50 | }) 51 | 52 | const restoreOriginalToJSON = [ 53 | overwriteProperty(Number.prototype, 'toJSON', () => 'number'), 54 | overwriteProperty(BigInt.prototype, 'toJSON', () => 'bigint'), 55 | overwriteProperty(String.prototype, 'toJSON', () => 'string'), 56 | overwriteProperty(Boolean.prototype, 'toJSON', () => 'boolean'), 57 | ] 58 | 59 | try { 60 | expect(test({ 61 | number: 42, 62 | bigint: BigInt(42), 63 | string: 'test', 64 | boolean: true, 65 | null: null, 66 | undefined 67 | })).to.be.true 68 | expect(test({ 69 | number: 43, 70 | string: 'test', 71 | boolean: true, 72 | null: null, 73 | undefined 74 | })).to.be.false 75 | } finally { 76 | restoreOriginalToJSON.forEach(restore => restore()) 77 | } 78 | }) 79 | 80 | it('compares objects by value', () => { 81 | const value = { b: 1 } 82 | const test = guard({ prop: value }) 83 | 84 | expect(test({ prop: value })).to.be.true 85 | expect(test({ prop: { b: 1 } })).to.be.false 86 | }) 87 | 88 | function overwriteProperty(obj: any, prop: string, value: unknown) { 89 | const original = obj[prop] 90 | obj[prop] = value 91 | return () => { obj[prop] = original } 92 | } 93 | }) 94 | -------------------------------------------------------------------------------- /packages/sql/src/interpreters.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Condition, 3 | CompoundCondition, 4 | FieldCondition, 5 | Comparable 6 | } from '@ucast/core'; 7 | import { SqlOperator } from './interpreter'; 8 | 9 | export const eq: SqlOperator = (condition, query) => { 10 | return query.where(condition.field, '=', condition.value); 11 | }; 12 | 13 | export const ne: typeof eq = (condition, query) => { 14 | return query.where(condition.field, '<>', condition.value); 15 | }; 16 | 17 | export const lt: SqlOperator> = (condition, query) => { 18 | return query.where(condition.field, '<', condition.value); 19 | }; 20 | 21 | export const lte: SqlOperator> = (condition, query) => { 22 | return query.where(condition.field, '<=', condition.value); 23 | }; 24 | 25 | export const gt: SqlOperator> = (condition, query) => { 26 | return query.where(condition.field, '>', condition.value); 27 | }; 28 | 29 | export const gte: SqlOperator> = (condition, query) => { 30 | return query.where(condition.field, '>=', condition.value); 31 | }; 32 | 33 | export const exists: SqlOperator> = (condition, query) => { 34 | return query.whereRaw(`${query.field(condition.field)} is ${condition.value ? 'not ' : ''}null`); 35 | }; 36 | 37 | function manyParamsOperator(name: string): SqlOperator> { 38 | return (condition, query) => { 39 | return query.whereRaw( 40 | `${query.field(condition.field)} ${name}(${query.manyParams(condition.value).join(', ')})`, 41 | ...condition.value 42 | ); 43 | }; 44 | } 45 | 46 | export const within = manyParamsOperator('in'); 47 | export const nin = manyParamsOperator('not in'); 48 | 49 | export const mod: SqlOperator> = (condition, query) => { 50 | const params = query.manyParams(condition.value); 51 | const sql = `mod(${query.field(condition.field)}, ${params[0]}) = ${params[1]}`; 52 | return query.whereRaw(sql, ...condition.value); 53 | }; 54 | 55 | type IElemMatch = SqlOperator>; 56 | export const elemMatch: IElemMatch = (condition, query, { interpret }) => { 57 | return query.usingFieldPrefix(condition.field, () => interpret(condition.value, query)); 58 | }; 59 | 60 | export const regex: SqlOperator> = (condition, query) => { 61 | const sql = query.options.regexp( 62 | query.field(condition.field), 63 | query.param(), 64 | condition.value.ignoreCase 65 | ); 66 | return query.whereRaw(sql, condition.value.source); 67 | }; 68 | 69 | function compoundOperator(combinator: 'and' | 'or', isInverted = false) { 70 | return ((node, query, { interpret }) => { 71 | const childQuery = query.child(); 72 | node.value.forEach(condition => interpret(condition, childQuery)); 73 | return query.merge(childQuery, combinator, isInverted); 74 | }) as SqlOperator; 75 | } 76 | 77 | export const not = compoundOperator('and', true); 78 | export const and = compoundOperator('and'); 79 | export const or = compoundOperator('or'); 80 | export const nor = compoundOperator('or', true); 81 | -------------------------------------------------------------------------------- /packages/sql/spec/mikro-orm.spec.ts: -------------------------------------------------------------------------------- 1 | import { FieldCondition } from '@ucast/core' 2 | import { MikroORM, Collection, EntitySchema, QueryBuilder } from 'mikro-orm' 3 | import { interpret } from '../src/lib/mikro-orm' 4 | import { expect } from './specHelper' 5 | 6 | type Depromisify> = T extends Promise ? A : never 7 | type OrmContext = Depromisify> 8 | 9 | describe('Condition interpreter for MikroORM', () => { 10 | let orm: OrmContext['orm'] 11 | let User: OrmContext['User'] 12 | 13 | before(async () => { 14 | const ctx = await configureORM() 15 | orm = ctx.orm 16 | User = ctx.User 17 | }) 18 | 19 | after(async () => { 20 | await orm.close() 21 | }) 22 | 23 | it('returns a `QueryBuilder`', () => { 24 | const condition = new FieldCondition('eq', 'name', 'test') 25 | const query = interpret(condition, orm.em.createQueryBuilder(User).select([])) 26 | 27 | expect(query).to.be.instanceof(QueryBuilder) 28 | expect(query.getQuery()).to.equal('select * from `user` as `e0` where (`name` = ?)') 29 | }) 30 | 31 | it('properly binds parameters for "IN" operator', () => { 32 | const condition = new FieldCondition('in', 'age', [1, 2, 3]) 33 | const query = interpret(condition, orm.em.createQueryBuilder(User).select([])) 34 | 35 | expect(query.getQuery()).to.equal('select * from `user` as `e0` where (`age` in(?, ?, ?))') 36 | }) 37 | 38 | it('automatically inner joins relation when condition is set on relation field', () => { 39 | const condition = new FieldCondition('eq', 'projects.name', 'test') 40 | const query = interpret(condition, orm.em.createQueryBuilder(User).select([])) 41 | 42 | expect(query.getQuery()).to.equal([ 43 | 'select *', 44 | 'from `user` as `e0`', 45 | 'inner join `project` as `projects` on `e0`.`id` = `projects`.`user_id`', 46 | 'where (`projects`.`name` = ?)' 47 | ].join(' ')) 48 | }) 49 | }) 50 | 51 | async function configureORM() { 52 | class User { 53 | constructor( 54 | public id: number, 55 | public name: string, 56 | public projects?: Collection 57 | ) { 58 | this.projects = projects || new Collection(this) 59 | } 60 | } 61 | 62 | class Project { 63 | constructor( 64 | public id: number, 65 | public name: string, 66 | public user: User 67 | ) {} 68 | } 69 | 70 | const UserSchema = new EntitySchema({ 71 | class: User, 72 | properties: { 73 | id: { type: 'number', primary: true }, 74 | name: { type: 'string' }, 75 | projects: { 76 | type: 'Project', 77 | reference: '1:m', 78 | inversedBy: 'user' 79 | } 80 | } 81 | }) 82 | const ProjectSchema = new EntitySchema({ 83 | class: Project, 84 | properties: { 85 | id: { type: 'number', primary: true }, 86 | name: { type: 'string' }, 87 | user: { type: 'User', reference: 'm:1' }, 88 | } 89 | }) 90 | 91 | const orm = await MikroORM.init({ 92 | entities: [UserSchema, ProjectSchema], 93 | dbName: ':memory:', 94 | type: 'sqlite', 95 | }) 96 | 97 | return { User, Project, orm } 98 | } 99 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UCAST - Universal Conditions AST 2 | 3 | ![build](https://github.com/stalniy/ucast/workflows/CI/badge.svg) 4 | [![CASL codecov](https://codecov.io/gh/stalniy/ucast/branch/master/graph/badge.svg)](https://codecov.io/gh/stalniy/ucast) 5 | [![UCAST join the chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/stalniy-ucast/community) 6 | 7 | `ucast` is a low level library that helps to create awesome things! It aims to be a universal way to represent a set of conditions that can be transferred between APIs and databases. 8 | 9 | ## Terms 10 | 11 | To get introduction about what is parser, interpreter, conditions AST and translator, please check the [README file of @ucast/core](./packages/core/README.md) 12 | 13 | ## What can I do with it? 14 | 15 | 1. You can translate an HTTP request query string into SQL, Mongo, ElasticSearch or anything you can imagine. 16 | 2. You can execute MongoDB query in javascript runtime 17 | 3. You can create an expressive query builder for SQL 18 | 19 | Generally speaking, `ucast` can help you to transfer conditions somewhere or interpret them in any way. 20 | 21 | ## Ecosystem 22 | 23 | All packages support nodejs 8+ and ES5 compatible browsers (IE 9+) 24 | 25 | | Project | Status | Description | 26 | |-------------------|--------------------------------------|-------------| 27 | | [@ucast/core] | [![@ucast/core-status]][@ucast/core-package] | conditions AST and helpers | 28 | | [@ucast/js] | [![@ucast/js-status]][@ucast/js-package] | ucast JavaScript interpreter | 29 | | [@ucast/mongo] | [![@ucast/mongo-status]][@ucast/mongo-package] | [MongoDB query] parser | 30 | | [@ucast/mongo2js] | [![@ucast/mongo2js-status]][@ucast/mongo2js-package] | Evaluates [MongoDB query] in JavaScript runtime | 31 | | [@ucast/sql] | [![@ucast/sql-status]][@ucast/sql-package] | SQL query interpreter + integrations with major ORMs | 32 | 33 | 34 | [MongoDB query]: http://docs.mongodb.org/manual/reference/operator/query/ 35 | 36 | [@ucast/core]: packages/core 37 | [@ucast/js]: packages/js 38 | [@ucast/mongo]: packages/mongo 39 | [@ucast/mongo2js]: packages/mongo2js 40 | [@ucast/sql]: packages/sql 41 | 42 | [@ucast/core-status]: https://img.shields.io/npm/v/@ucast/core.svg 43 | [@ucast/js-status]: https://img.shields.io/npm/v/@ucast/js.svg 44 | [@ucast/mongo-status]: https://img.shields.io/npm/v/@ucast/mongo.svg 45 | [@ucast/mongo2js-status]: https://img.shields.io/npm/v/@ucast/mongo2js.svg 46 | [@ucast/sql-status]: https://img.shields.io/npm/v/@ucast/sql.svg 47 | 48 | [@ucast/core-package]: https://www.npmjs.com/package/@ucast/core 49 | [@ucast/js-package]: https://www.npmjs.com/package/@ucast/js 50 | [@ucast/mongo-package]: https://www.npmjs.com/package/@ucast/mongo 51 | [@ucast/mongo2js-package]: https://www.npmjs.com/package/@ucast/mongo 52 | [@ucast/sql-package]: https://www.npmjs.com/package/@ucast/sql 53 | 54 | ## Want to help? 55 | 56 | Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for [contributing] 57 | 58 | ## License 59 | 60 | [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 61 | 62 | [contributing]: https://github.com/stalniy/ucast/blob/master/CONTRIBUTING.md 63 | -------------------------------------------------------------------------------- /packages/core/src/interpreter.ts: -------------------------------------------------------------------------------- 1 | import { Condition } from './Condition'; 2 | 3 | type ArgsExceptLast any> = 4 | F extends (a: any, c: any) => any 5 | ? Parameters<(condition: Condition) => 0> 6 | : F extends (a: any, b: any, c: any) => any 7 | ? Parameters<(condition: Condition, value: Parameters[1]) => 0> 8 | : Parameters<( 9 | condition: Condition, 10 | value: Parameters[1], 11 | options: Parameters[2], 12 | ...args: unknown[] 13 | ) => 0>; 14 | 15 | export type Interpreter = (condition: T, ...args: any[]) => R; 16 | export type AnyInterpreter = Interpreter; 17 | export interface InterpretationContext { 18 | interpret(...args: ArgsExceptLast): ReturnType; 19 | } 20 | 21 | function getInterpreter>( 22 | interpreters: T, 23 | operator: keyof T 24 | ) { 25 | const interpret = interpreters[operator]; 26 | 27 | if (typeof interpret !== 'function') { 28 | throw new Error(`Unable to interpret "${String(operator)}" condition. Did you forget to register interpreter for it?`); 29 | } 30 | 31 | return interpret; 32 | } 33 | 34 | export interface InterpreterOptions { 35 | numberOfArguments?: 1 | 2 | 3 36 | getInterpreterName?(condition: Condition, context: this): string 37 | } 38 | 39 | function defaultInterpreterName(condition: Condition) { 40 | return condition.operator; 41 | } 42 | 43 | export function createInterpreter( 44 | interpreters: Record, 45 | rawOptions?: U 46 | ) { 47 | const options = rawOptions as U & InterpreterOptions; 48 | const getInterpreterName = options && options.getInterpreterName || defaultInterpreterName; 49 | let interpret: InterpretationContext['interpret']; 50 | 51 | switch (options ? options.numberOfArguments : 0) { 52 | case 1: 53 | interpret = ((condition) => { 54 | const interpreterName = getInterpreterName(condition, options); 55 | const interpretOperator = getInterpreter(interpreters, interpreterName); 56 | return interpretOperator(condition, defaultContext); 57 | }); 58 | break; 59 | case 3: 60 | interpret = (( 61 | condition: ArgsExceptLast[0], 62 | value: ArgsExceptLast[1], 63 | params: ArgsExceptLast[2] 64 | ) => { 65 | const interpreterName = getInterpreterName(condition, options); 66 | const interpretOperator = getInterpreter(interpreters, interpreterName); 67 | return interpretOperator(condition, value, params, defaultContext); 68 | }) as unknown as InterpretationContext['interpret']; 69 | break; 70 | default: 71 | interpret = ((condition, value) => { 72 | const interpreterName = getInterpreterName(condition, options); 73 | const interpretOperator = getInterpreter(interpreters, interpreterName); 74 | return interpretOperator(condition, value, defaultContext); 75 | }) as InterpretationContext['interpret']; 76 | break; 77 | } 78 | 79 | const defaultContext = { 80 | ...options, 81 | interpret, 82 | } as InterpretationContext & U; 83 | 84 | return defaultContext.interpret; 85 | } 86 | -------------------------------------------------------------------------------- /packages/mongo2js/src/factory.ts: -------------------------------------------------------------------------------- 1 | import { createTranslatorFactory, ParsingInstruction, Condition, ITSELF } from '@ucast/core'; 2 | import { 3 | MongoQuery, 4 | MongoQueryParser, 5 | MongoQueryFieldOperators, 6 | allParsingInstructions, 7 | defaultParsers 8 | } from '@ucast/mongo'; 9 | import { 10 | createJsInterpreter, 11 | allInterpreters, 12 | JsInterpreter, 13 | JsInterpretationOptions, 14 | compare 15 | } from '@ucast/js'; 16 | 17 | type ThingFilter = { 18 | (object: T): boolean 19 | ast: Condition 20 | }; 21 | 22 | interface HasToJSON { 23 | toJSON(): unknown 24 | } 25 | 26 | function toPrimitive(value: unknown) { 27 | if (value === null || typeof value !== 'object') { 28 | return value; 29 | } 30 | 31 | if (value instanceof Date) { 32 | return value.getTime(); 33 | } 34 | 35 | if (value && typeof (value as HasToJSON).toJSON === 'function') { 36 | return (value as HasToJSON).toJSON(); 37 | } 38 | 39 | return value; 40 | } 41 | 42 | const comparePrimitives: typeof compare = (a, b) => compare(toPrimitive(a), toPrimitive(b)); 43 | 44 | export interface FactoryOptions extends JsInterpretationOptions { 45 | forPrimitives: boolean 46 | } 47 | 48 | export type Filter = < 49 | T = Record, 50 | Q extends MongoQuery = MongoQuery 51 | >(query: Q) => ThingFilter; 52 | 53 | export type PrimitiveMongoQuery = MongoQueryFieldOperators & Partial<{ 54 | $and: MongoQueryFieldOperators[], 55 | $or: MongoQueryFieldOperators[], 56 | $nor: MongoQueryFieldOperators[] 57 | }>; 58 | export type PrimitiveFilter = < 59 | T, 60 | Q extends PrimitiveMongoQuery = PrimitiveMongoQuery 61 | >(query: Q) => ThingFilter; 62 | 63 | type FilterType = T['forPrimitives'] extends true 64 | ? PrimitiveFilter 65 | : Filter; 66 | 67 | export function createFactory< 68 | T extends Record>, 69 | I extends Record>, 70 | P extends { forPrimitives?: true } 71 | >(instructions: T, interpreters: I, options?: Partial & P): FilterType

{ 72 | const parser = new MongoQueryParser(instructions); 73 | const interpret = createJsInterpreter(interpreters, { 74 | compare: comparePrimitives, 75 | ...options 76 | }); 77 | 78 | if (options && options.forPrimitives) { 79 | const params = { field: ITSELF }; 80 | const parse = parser.parse; 81 | parser.setParse(query => parse(query, params)); 82 | } 83 | 84 | return createTranslatorFactory(parser.parse, interpret) as any; 85 | } 86 | 87 | export const guard = createFactory(allParsingInstructions, allInterpreters); 88 | 89 | const compoundOperators = ['$and', '$or'] as const; 90 | const allPrimitiveParsingInstructions = compoundOperators.reduce((instructions, name) => { 91 | instructions[name] = { ...instructions[name], type: 'field' } as any; 92 | return instructions; 93 | }, { 94 | ...allParsingInstructions, 95 | $nor: { 96 | ...allParsingInstructions.$nor, 97 | type: 'field', 98 | parse: defaultParsers.compound 99 | } 100 | }); 101 | 102 | export const squire = createFactory(allPrimitiveParsingInstructions, allInterpreters, { 103 | forPrimitives: true 104 | }); 105 | export const filter = guard; // TODO: remove in next major version 106 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from '@rollup/plugin-babel'; 2 | import resolve from '@rollup/plugin-node-resolve'; 3 | import commonjs from '@rollup/plugin-commonjs'; 4 | import { terser } from 'rollup-plugin-terser'; 5 | import { dirname, basename, extname } from 'path'; 6 | 7 | const output = (config) => { 8 | let prop = 'dir'; 9 | let path = `dist/${config.id}${config.subpath}`; 10 | 11 | if (config.ext) { 12 | prop = 'file'; 13 | path += `/${basename(config.input, extname(config.input))}${config.ext}`; 14 | } 15 | 16 | return { 17 | [prop]: path, 18 | format: config.format, 19 | name: config.name, 20 | globals: config.globals, 21 | }; 22 | }; 23 | 24 | const build = config => ({ 25 | input: config.input, 26 | external: config.external, 27 | output: { 28 | sourcemap: true, 29 | ...output(config), 30 | plugins: [ 31 | config.minify 32 | ? terser({ 33 | mangle: { properties: { regex: /^_[a-z]/i } } 34 | }) 35 | : null 36 | ] 37 | }, 38 | plugins: [ 39 | resolve({ 40 | mainFields: ['module', 'main', 'browser'], 41 | extensions: ['.js', '.mjs', '.ts'], 42 | }), 43 | commonjs(), 44 | babel({ 45 | rootMode: 'upward', 46 | extensions: ['.js', '.mjs', '.ts'], 47 | inputSourceMap: config.useInputSourceMaps, 48 | babelHelpers: 'bundled', 49 | caller: { 50 | output: config.type, 51 | } 52 | }), 53 | ...(config.plugins || []) 54 | ] 55 | }); 56 | 57 | function parseOptions(overrideOptions) { 58 | const options = { 59 | external: [], 60 | input: 'src/index.ts', 61 | subpath: '', 62 | useInputSourceMaps: !!process.env.USE_SRC_MAPS, 63 | minify: process.env.NODE_ENV === 'production' 64 | }; 65 | 66 | if (overrideOptions.input) { 67 | options.input = overrideOptions.input[0]; 68 | options.subpath = dirname(options.input).replace(/^src/, ''); 69 | } 70 | 71 | if (typeof overrideOptions.external === 'string') { 72 | options.external = overrideOptions.external.split(','); 73 | } else if (overrideOptions.external) { 74 | options.external = options.external.concat(overrideOptions.external); 75 | } 76 | 77 | if (typeof overrideOptions.globals === 'string') { 78 | options.globals = overrideOptions.globals.split(','); 79 | } 80 | 81 | if (options.globals) { 82 | options.globals = options.globals.reduce((map, chunk) => { 83 | const [moduleId, globalName] = chunk.split(':'); 84 | map[moduleId] = globalName; 85 | return map; 86 | }, {}); 87 | options.external.push(...Object.keys(options.globals)); 88 | } 89 | 90 | return options; 91 | } 92 | 93 | export default (overrideOptions) => { 94 | const builds = [ 95 | { id: 'es6m', type: 'es6', format: 'es', ext: '.mjs' }, 96 | { id: 'es6c', type: 'es6', format: 'cjs' }, 97 | { id: 'es5m', type: 'es5', format: 'es' }, 98 | { id: 'umd', type: 'es5', format: 'umd', name: overrideOptions.name }, 99 | ]; 100 | const config = parseOptions(overrideOptions); 101 | const buildTypes = process.env.BUILD_TYPES 102 | ? process.env.BUILD_TYPES.split(',') 103 | : builds.map(buildConfig => buildConfig.id); 104 | 105 | return builds 106 | .filter(buildType => buildTypes.includes(buildType.id)) 107 | .map(buildType => build({ ...buildType, ...config })); 108 | }; 109 | -------------------------------------------------------------------------------- /packages/mongo2js/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | # [1.4.0](https://github.com/stalniy/ucast/compare/@ucast/mongo2js@1.3.4...@ucast/mongo2js@1.4.0) (2025-02-26) 6 | 7 | 8 | ### Features 9 | 10 | * ensures that `toJSON` is not called on primitives ([#54](https://github.com/stalniy/ucast/issues/54)) ([cc70754](https://github.com/stalniy/ucast/commit/cc707543119ba4278e63b2ee7894460756f3e61d)) 11 | 12 | ## [1.3.4](https://github.com/stalniy/ucast/compare/@ucast/mongo2js@1.3.3...@ucast/mongo2js@1.3.4) (2023-02-15) 13 | 14 | 15 | ### Bug Fixes 16 | 17 | * adds typings to ESM exports in package.json ([1ffb703](https://github.com/stalniy/ucast/commit/1ffb7033a6d70ee4eb5f9d3178bcb4df37da835e)) 18 | * updates metadata in package.json ([2fa89f5](https://github.com/stalniy/ucast/commit/2fa89f573eeb033c657b7c54b4640a856859f766)) 19 | 20 | ## [1.3.3](https://github.com/stalniy/ucast/compare/@ucast/mongo2js@1.3.2...@ucast/mongo2js@1.3.3) (2021-07-15) 21 | 22 | 23 | ### Bug Fixes 24 | 25 | * remove type commonjs from package.json to improve webpack compat ([#28](https://github.com/stalniy/ucast/issues/28)) ([6b1ad28](https://github.com/stalniy/ucast/commit/6b1ad289d7b4f9945f08f29efd952069efd6c8c9)) 26 | 27 | ## [1.3.2](https://github.com/stalniy/ucast/compare/@ucast/mongo2js@1.3.1...@ucast/mongo2js@1.3.2) (2021-01-10) 28 | 29 | 30 | ### Bug Fixes 31 | 32 | * marks packages as commonjs by default with a separate ESM entry ([a3f4896](https://github.com/stalniy/ucast/commit/a3f48961a93b5951cb92d9954297cd12754d3ff1)) 33 | 34 | ## [1.3.1](https://github.com/stalniy/ucast/compare/@ucast/mongo2js@1.3.0...@ucast/mongo2js@1.3.1) (2020-10-17) 35 | 36 | 37 | ### Bug Fixes 38 | 39 | * **package:** upgrades to the latest @ucast/js ([4d387d3](https://github.com/stalniy/ucast/commit/4d387d3c22e9f4682f32c246111f69c2f92f3964)) 40 | 41 | # [1.3.0](https://github.com/stalniy/ucast/compare/@ucast/mongo2js@1.2.0...@ucast/mongo2js@1.3.0) (2020-08-20) 42 | 43 | 44 | ### Features 45 | 46 | * **esm:** adds ESM support via dual loading in package.json for latest Node.js version ([c730f95](https://github.com/stalniy/ucast/commit/c730f9598a4c62589c612403c0ac59ba4aa1600e)), closes [#10](https://github.com/stalniy/ucast/issues/10) 47 | 48 | # [1.2.0](https://github.com/stalniy/ucast/compare/@ucast/mongo2js@1.1.1...@ucast/mongo2js@1.2.0) (2020-08-18) 49 | 50 | 51 | ### Features 52 | 53 | * **mongo2js:** adds `squire` function for primitives and renames `filter` to `guard` ([683d813](https://github.com/stalniy/ucast/commit/683d81367e60282d0828f5b3e2fe1603c27f8f4e)), closes [#9](https://github.com/stalniy/ucast/issues/9) 54 | * **mongo2js:** adds support for compound operators in primitive mongo query ([a4273a6](https://github.com/stalniy/ucast/commit/a4273a63a9442a130225681cfca75326c9799f42)), closes [#9](https://github.com/stalniy/ucast/issues/9) 55 | 56 | ## [1.1.1](https://github.com/stalniy/ucast/compare/@ucast/mongo2js@1.1.0...@ucast/mongo2js@1.1.1) (2020-08-11) 57 | 58 | 59 | ### Bug Fixes 60 | 61 | * **mongo2js:** removes `workspace:` protocol from deps ([5b6862d](https://github.com/stalniy/ucast/commit/5b6862d2c15573baf9578761372f0d19614922de)) 62 | 63 | # [1.1.0](https://github.com/stalniy/ucast/compare/@ucast/mongo2js@1.0.0...@ucast/mongo2js@1.1.0) (2020-08-11) 64 | 65 | 66 | ### Features 67 | 68 | * **filter:** makes it possible to check complex values like ObjectId and Dates ([79a8a49](https://github.com/stalniy/ucast/commit/79a8a498387e0eba9adb1ebb147e7f25c39e9498)) 69 | 70 | # 1.0.0 (2020-08-08) 71 | 72 | 73 | ### Features 74 | 75 | * **translator:** creates mongo to js package ([383143b](https://github.com/stalniy/ucast/commit/383143bc6e96e7c8af07f874bf3f3ad464c34db1)) 76 | -------------------------------------------------------------------------------- /packages/sql/spec/typeorm.spec.ts: -------------------------------------------------------------------------------- 1 | import { FieldCondition } from '@ucast/core' 2 | import { 3 | EntitySchema, 4 | createConnection, 5 | SelectQueryBuilder 6 | } from 'typeorm' 7 | import { interpret } from '../src/lib/typeorm' 8 | import { expect } from './specHelper' 9 | 10 | type Depromisify> = T extends Promise ? A : never 11 | type OrmContext = Depromisify> 12 | 13 | describe('Condition interpreter for TypeORM', () => { 14 | let conn: OrmContext['conn'] 15 | let User: OrmContext['User'] 16 | 17 | before(async () => { 18 | const ctx = await configureORM() 19 | conn = ctx.conn 20 | User = ctx.User 21 | }) 22 | 23 | after(async () => { 24 | await conn.close() 25 | }) 26 | 27 | it('returns a `SelectQueryBuilder`', () => { 28 | const condition = new FieldCondition('eq', 'name', 'test') 29 | const query = interpret(condition, conn.createQueryBuilder(User, 'u')) 30 | 31 | expect(query).to.be.instanceof(SelectQueryBuilder) 32 | expect(query.getQuery()).to.equal([ 33 | 'SELECT "u"."id" AS "u_id", "u"."name" AS "u_name"', 34 | 'FROM "user" "u"', 35 | 'WHERE "name" = :0' 36 | ].join(' ')) 37 | expect(query.getParameters()).to.eql({ 0: 'test' }) 38 | }) 39 | 40 | it('properly binds parameters for "IN" operator', () => { 41 | const condition = new FieldCondition('in', 'age', [1, 2, 3]) 42 | const query = interpret(condition, conn.createQueryBuilder(User, 'u')) 43 | 44 | expect(query.getQuery()).to.equal([ 45 | 'SELECT "u"."id" AS "u_id", "u"."name" AS "u_name"', 46 | 'FROM "user" "u"', 47 | 'WHERE "age" in(:0, :1, :2)' 48 | ].join(' ')) 49 | 50 | expect(query.getParameters()).to.eql({ 51 | 0: 1, 52 | 1: 2, 53 | 2: 3 54 | }) 55 | }) 56 | 57 | it('automatically inner joins relation when condition is set on relation field', () => { 58 | const condition = new FieldCondition('eq', 'projects.name', 'test') 59 | const query = interpret(condition, conn.createQueryBuilder(User, 'u')) 60 | 61 | expect(query.getQuery()).to.equal([ 62 | 'SELECT "u"."id" AS "u_id", "u"."name" AS "u_name"', 63 | 'FROM "user" "u"', 64 | 'INNER JOIN "project" "projects" ON "projects"."userId"="u"."id"', 65 | 'WHERE "projects"."name" = :0' 66 | ].join(' ')) 67 | expect(query.getParameters()).to.eql({ 0: 'test' }) 68 | }) 69 | }) 70 | 71 | async function configureORM() { 72 | class User { 73 | id!: number 74 | name!: string 75 | projects!: Project[] 76 | } 77 | 78 | class Project { 79 | id!: number 80 | name!: string 81 | user!: User 82 | } 83 | 84 | const UserSchema = new EntitySchema({ 85 | name: 'User', 86 | target: User, 87 | columns: { 88 | id: { primary: true, type: 'int', generated: true }, 89 | name: { type: 'varchar' }, 90 | }, 91 | relations: { 92 | projects: { 93 | target: 'Project', 94 | type: 'one-to-many', 95 | inverseSide: 'user' 96 | } 97 | } 98 | }) 99 | 100 | const ProjectSchema = new EntitySchema({ 101 | name: 'Project', 102 | target: Project, 103 | columns: { 104 | id: { primary: true, type: 'int', generated: true }, 105 | name: { type: 'varchar' }, 106 | }, 107 | relations: { 108 | user: { target: 'User', type: 'many-to-one' } 109 | } 110 | }) 111 | 112 | const conn = await createConnection({ 113 | type: 'sqlite', 114 | database: ':memory:', 115 | entities: [UserSchema, ProjectSchema] 116 | }) 117 | 118 | return { User, Project, conn } 119 | } 120 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import tseslint from 'typescript-eslint'; 2 | import importPlugin from "eslint-plugin-import"; 3 | import globals from "globals"; 4 | import js from "@eslint/js" 5 | import { defineConfig } from 'eslint/config'; 6 | import stylisticJs from '@stylistic/eslint-plugin-js' 7 | import stylisticTs from '@stylistic/eslint-plugin-ts' 8 | 9 | export default defineConfig( 10 | { 11 | ignores: ['**/dist/**'], 12 | }, 13 | js.configs.recommended, 14 | tseslint.configs.recommended, 15 | tseslint.configs.stylistic, 16 | importPlugin.flatConfigs.typescript, 17 | { 18 | plugins: { 19 | '@stylistic/js': stylisticJs, 20 | '@stylistic/ts': stylisticTs, 21 | '@typescript-eslint': tseslint.plugin, 22 | }, 23 | rules: { 24 | "@typescript-eslint/consistent-type-definitions": "off", 25 | "@typescript-eslint/no-empty-object-type": "off", 26 | "@typescript-eslint/prefer-for-of": "off", 27 | "@typescript-eslint/no-empty-function": "off", 28 | "@typescript-eslint/no-unused-vars": [ 29 | "error", 30 | { 31 | "args": "all", 32 | "argsIgnorePattern": "^_", 33 | "caughtErrors": "all", 34 | "caughtErrorsIgnorePattern": "^_", 35 | "destructuredArrayIgnorePattern": "^_" 36 | } 37 | ] 38 | } 39 | }, 40 | { 41 | files: ["**/*.ts", "**/*.js"], 42 | languageOptions: { 43 | parser: tseslint.parser, 44 | ecmaVersion: 5, 45 | sourceType: "script", 46 | parserOptions: { 47 | project: "./tsconfig.json", 48 | }, 49 | }, 50 | settings: { 51 | "import/parsers": { 52 | "@typescript-eslint/parser": [".ts", ".tsx", ".d.ts"], 53 | }, 54 | "import/resolver": { 55 | node: { 56 | extensions: [".mjs", ".js", ".json", ".ts", ".d.ts"], 57 | }, 58 | }, 59 | "import/extensions": [".js", ".mjs", ".jsx", ".ts", ".tsx", ".d.ts"], 60 | "import/external-module-folders": ["node_modules", "node_modules/@types"], 61 | }, 62 | rules: { 63 | "@stylistic/js/max-len": ["error", { 64 | code: 100, 65 | ignoreComments: true, 66 | ignoreStrings: true, 67 | ignoreTemplateLiterals: true, 68 | }], 69 | 70 | "@stylistic/js/lines-between-class-members": ["error", "always", { 71 | exceptAfterSingleLine: true, 72 | }], 73 | 74 | "@typescript-eslint/comma-dangle": "off", 75 | "no-redeclare": "off", 76 | "@typescript-eslint/no-redeclare": "off", 77 | "@typescript-eslint/ban-ts-comment": "off", 78 | "@typescript-eslint/ban-types": "off", 79 | "@typescript-eslint/no-explicit-any": "off", 80 | "@typescript-eslint/no-use-before-define": "off", 81 | "no-restricted-imports": ["error", { 82 | "patterns": [{ 83 | "group": ["**/dist/*"], 84 | "message": "Do not import compiled sources directly" 85 | }] 86 | }] 87 | }, 88 | }, 89 | { 90 | files: ["**/*.spec.{js,ts}"], 91 | languageOptions: { 92 | globals: { 93 | ...globals.mocha, 94 | ...globals.browser, 95 | }, 96 | }, 97 | rules: { 98 | "@stylistic/ts/semi": ["error", "never"], 99 | "@typescript-eslint/no-unused-expressions": "off", 100 | "import/no-extraneous-dependencies": "off", 101 | }, 102 | } 103 | ); 104 | -------------------------------------------------------------------------------- /packages/sql/src/interpreter.ts: -------------------------------------------------------------------------------- 1 | import { 2 | createInterpreter, 3 | Condition, 4 | InterpretationContext 5 | } from '@ucast/core'; 6 | import { DialectOptions } from './dialects'; 7 | 8 | export interface SqlQueryOptions extends Required { 9 | rootAlias?: string 10 | } 11 | 12 | export class Query { 13 | public readonly options!: SqlQueryOptions; 14 | private _fieldPrefix!: string; 15 | private _params: unknown[] = []; 16 | private _sql: string[] = []; 17 | private _joins: string[] = []; 18 | private _lastPlaceholderIndex = 1; 19 | private _targetQuery!: unknown; 20 | private _rootAlias!: string; 21 | 22 | constructor(options: SqlQueryOptions, fieldPrefix = '', targetQuery?: unknown) { 23 | this.options = options; 24 | this._fieldPrefix = fieldPrefix; 25 | this._targetQuery = targetQuery; 26 | this._rootAlias = options.rootAlias ? `${options.escapeField(options.rootAlias)}.` : ''; 27 | } 28 | 29 | field(rawName: string) { 30 | const name = this._fieldPrefix + rawName; 31 | const relationNameIndex = name.indexOf('.'); 32 | 33 | if (relationNameIndex === -1) { 34 | return this._rootAlias + this.options.escapeField(name); 35 | } 36 | 37 | const relationName = name.slice(0, relationNameIndex); 38 | const field = name.slice(relationNameIndex + 1); 39 | 40 | if (!this.options.joinRelation(relationName, this._targetQuery)) { 41 | return this.options.escapeField(field); 42 | } 43 | 44 | this._joins.push(relationName); 45 | return `${this.options.escapeField(relationName)}.${this.options.escapeField(field)}`; 46 | } 47 | 48 | param() { 49 | return this.options.paramPlaceholder(this._lastPlaceholderIndex + this._params.length); 50 | } 51 | 52 | manyParams(items: unknown[]) { 53 | const startIndex = this._lastPlaceholderIndex + this._params.length; 54 | return items.map((_, i) => this.options.paramPlaceholder(startIndex + i)); 55 | } 56 | 57 | child() { 58 | const query = new Query(this.options, this._fieldPrefix, this._targetQuery); 59 | query._lastPlaceholderIndex = this._lastPlaceholderIndex + this._params.length; 60 | return query; 61 | } 62 | 63 | where(field: string, operator: string, value?: unknown) { 64 | const sql = `${this.field(field)} ${operator} ${this.param()}`; 65 | return this.whereRaw(sql, value); 66 | } 67 | 68 | whereRaw(sql: string, ...values: unknown[]) { 69 | this._sql.push(sql); 70 | 71 | if (values) { 72 | this._params.push(...values); 73 | } 74 | 75 | return this; 76 | } 77 | 78 | merge(query: Query, operator: 'and' | 'or' = 'and', isInverted = false) { 79 | let sql = query._sql.join(` ${operator} `); 80 | 81 | if (sql[0] !== '(') { 82 | sql = `(${sql})`; 83 | } 84 | 85 | this._sql.push(`${isInverted ? 'not ' : ''}${sql}`); 86 | this._params.push(...query._params); 87 | return this; 88 | } 89 | 90 | usingFieldPrefix(prefix: string, callback: () => void) { 91 | const prevPrefix = this._fieldPrefix; 92 | 93 | try { 94 | this._fieldPrefix = `${prefix}.`; 95 | callback(); 96 | return this; 97 | } finally { 98 | this._fieldPrefix = prevPrefix; 99 | } 100 | } 101 | 102 | toJSON(): [string, unknown[], string[]] { 103 | return [this._sql.join(' and '), this._params, this._joins]; 104 | } 105 | } 106 | 107 | export type SqlOperator = ( 108 | condition: C, 109 | query: Query, 110 | context: InterpretationContext>, 111 | ) => Query; 112 | 113 | export function createSqlInterpreter(operators: Record>) { 114 | const interpret = createInterpreter>(operators); 115 | return (condition: Condition, options: SqlQueryOptions, targetQuery?: unknown) => { 116 | return interpret(condition, new Query(options, '', targetQuery)).toJSON(); 117 | }; 118 | } 119 | -------------------------------------------------------------------------------- /packages/js/src/interpreters.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CompoundCondition as Compound, 3 | FieldCondition as Field, 4 | DocumentCondition as Document, 5 | Condition, 6 | Comparable, 7 | ITSELF, 8 | } from '@ucast/core'; 9 | import { JsInterpreter as Interpret } from './types'; 10 | import { 11 | includes, 12 | testValueOrArray, 13 | isArrayAndNotNumericField, 14 | AnyObject, 15 | hasOwn, 16 | } from './utils'; 17 | import { getObjectFieldCursor } from './interpreter'; 18 | 19 | export const or: Interpret = (node, object, { interpret }) => { 20 | return node.value.some(condition => interpret(condition, object)); 21 | }; 22 | 23 | export const nor: typeof or = (node, object, context) => { 24 | return !or(node, object, context); 25 | }; 26 | 27 | export const and: Interpret = (node, object, { interpret }) => { 28 | return node.value.every(condition => interpret(condition, object)); 29 | }; 30 | 31 | export const not: Interpret = (node, object, { interpret }) => { 32 | return !interpret(node.value[0], object); 33 | }; 34 | 35 | export const eq: Interpret = (node, object, { compare, get }) => { 36 | const value = get(object, node.field); 37 | 38 | if (Array.isArray(value) && !Array.isArray(node.value)) { 39 | return includes(value, node.value, compare); 40 | } 41 | 42 | return compare(value, node.value) === 0; 43 | }; 44 | 45 | export const ne: typeof eq = (node, object, context) => { 46 | return !eq(node, object, context); 47 | }; 48 | 49 | export const lte = testValueOrArray((node, value, context) => { 50 | const result = context.compare(value, node.value); 51 | return result === 0 || result === -1; 52 | }); 53 | 54 | export const lt = testValueOrArray((node, value, context) => { 55 | return context.compare(value, node.value) === -1; 56 | }); 57 | export const gt = testValueOrArray((node, value, context) => { 58 | return context.compare(value, node.value) === 1; 59 | }); 60 | export const gte = testValueOrArray((node, value, context) => { 61 | const result = context.compare(value, node.value); 62 | return result === 0 || result === 1; 63 | }); 64 | 65 | export const exists: Interpret> = (node, object, { get }) => { 66 | if (node.field === ITSELF) { 67 | return typeof object !== 'undefined'; 68 | } 69 | 70 | const [item, field] = getObjectFieldCursor<{}>(object, node.field, get); 71 | const test = (value: {}) => { 72 | if (value == null) return Boolean(value) === node.value; 73 | return hasOwn(value, field) === node.value; 74 | }; 75 | 76 | return isArrayAndNotNumericField(item, field) ? item.some(test) : test(item); 77 | }; 78 | 79 | export const mod = testValueOrArray<[number, number], number>((node, value) => { 80 | return typeof value === 'number' && value % node.value[0] === node.value[1]; 81 | }); 82 | 83 | export const size: Interpret, AnyObject | unknown[]> = (node, object, { get }) => { 84 | const [items, field] = getObjectFieldCursor(object as AnyObject, node.field, get); 85 | const test = (item: unknown) => { 86 | const value = get(item, field); 87 | return Array.isArray(value) && value.length === node.value; 88 | }; 89 | 90 | return node.field !== ITSELF && isArrayAndNotNumericField(items, field) 91 | ? items.some(test) 92 | : test(items); 93 | }; 94 | 95 | export const regex = testValueOrArray((node, value) => { 96 | return typeof value === 'string' && node.value.test(value); 97 | }); 98 | 99 | export const within = testValueOrArray((node, object, { compare }) => { 100 | return includes(node.value, object, compare); 101 | }); 102 | 103 | export const nin: typeof within = (node, object, context) => !within(node, object, context); 104 | 105 | export const all: Interpret> = (node, object, { compare, get }) => { 106 | const value = get(object, node.field); 107 | return Array.isArray(value) && node.value.every(v => includes(value, v, compare)); 108 | }; 109 | 110 | export const elemMatch: Interpret> = (node, object, { interpret, get }) => { 111 | const value = get(object, node.field); 112 | return Array.isArray(value) && value.some(v => interpret(node.value, v)); 113 | }; 114 | 115 | type WhereFunction = (this: AnyObject) => boolean; 116 | export const where: Interpret, AnyObject> = (node, object) => { 117 | return node.value.call(object); 118 | }; 119 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to UCAST 2 | 3 | I would love for you to contribute to UCAST and help make it even better than it is today! As a contributor, here are the guidelines I would like you to follow: 4 | 5 | - [Question or Problem?](#question) 6 | - [Issues and Bugs](#issue) 7 | - [Feature Requests](#feature) 8 | - [Submission Guidelines](#submit) 9 | - [Coding Rules](#rules) 10 | - [Commit Message Guidelines](#commit) 11 | 12 | ## Got a Question or Problem? 13 | 14 | Do not open issues for general support questions as I want to keep GitHub issues for bug reports and feature requests. You've got much better chances of getting your question answered on [stackoverflow](https://stackoverflow.com). 15 | 16 | ## Found a Bug? 17 | 18 | If you find a bug in the source code, you can help by [submitting an issue](#submit-issue) or even better, you can [submit a Pull Request](#submit-pr) with a fix. 19 | 20 | ## Missing a Feature? 21 | 22 | You can *request* a new feature by [submitting an issue](#submit-issue) to this GitHub Repository. If you would like to *implement* a new feature, please submit an issue with a proposal for your work first, to be sure that somebody else hasn't started to do the same. 23 | 24 | ## Submission Guidelines 25 | 26 | ### Submitting an Issue 27 | 28 | Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available. 29 | 30 | Please provide steps to reproduce for found bug (using http://plnkr.co, https://codesandbox.io/, https://repl.it/ or similar), this will help to understand and fix the issue faster. 31 | 32 | ### Submitting a Pull Request (PR) 33 | 34 | Before you submit your Pull Request (PR) consider the following guidelines: 35 | 36 | * Search [GitHub](https://github.com/stalniy/ucast/pulls) for an open or closed PR 37 | that relates to your submission. You don't want to duplicate effort. 38 | 39 | * Fork the project and setup it (UCAST uses [pnpm](https://pnpm.js.org/) for monorepo management): 40 | 41 | ```sh 42 | # replace ${YOUR_GITHUB_USER_NAME} with your github username 43 | git clone git@github.com:${YOUR_GITHUB_USER_NAME}/ucast.git 44 | # install pnpm, other ways at https://pnpm.js.org/en/installation 45 | npx pnpm add -g pnpm 46 | cd ucast 47 | pnpm recursive i 48 | pnpm -r build 49 | ``` 50 | 51 | * Make your changes in a new git branch (fork master branch): 52 | 53 | ```sh 54 | git checkout -b my-fix-branch master 55 | ``` 56 | 57 | * **include appropriate test cases**. 58 | * Follow defined [Coding Rules](#rules). 59 | * Run all test suites `pnpm test` 60 | * Commit your changes using a descriptive commit message that follows defined [commit message conventions](#commit). Adherence to these conventions is necessary because release notes are automatically generated from these messages using [semantic-release](https://semantic-release.gitbook.io/semantic-release/). 61 | * Push your branch to GitHub: 62 | 63 | ```sh 64 | git push origin my-fix-branch 65 | ``` 66 | 67 | * In GitHub, send a pull request to `ucast:master`. 68 | * If somebody from project contributors suggest changes then: 69 | * Make the required updates. 70 | * Re-run all test suites to ensure tests are still passing. 71 | * Rebase your branch and force push to your GitHub repository (this will update your Pull Request). Basically you can use `git commit -a --amend` and `git push --force origin my-fix-branch` in order to keep single commit in the feature branch. 72 | 73 | That's it! Thank you for your contribution! 74 | 75 | ## Coding Rules 76 | 77 | To ensure consistency throughout the source code, keep these rules in mind as you are working: 78 | 79 | * All features or bug fixes **must be tested** by one or more specs (unit-tests). 80 | * All public API methods **must be documented** in docs-src/src/content/pages. 81 | * Project follows [Airbnb's TypeScript Style Guide][js-style-guide] with [some exceptions](.eslintrc). All these will be checked by CI when you submit your PR 82 | 83 | ## Commit Message Guidelines 84 | 85 | The project have very precise rules over how git commit messages can be formatted. This leads to **more readable messages** that are easy to follow when looking through the **project history**. But also, git history is used to **generate the change log**. 86 | 87 | The commit message format is borrowed from Angular projects and you can find [more details in this document][commit-message-format] 88 | 89 | [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# 90 | [github]: https://github.com/stalniy/ucast 91 | [js-style-guide]: https://github.com/airbnb/javascript 92 | -------------------------------------------------------------------------------- /packages/sql/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ucast/sql", 3 | "version": "0.0.1", 4 | "description": "git@github.com:stalniy/ucast.git", 5 | "main": "dist/es6c/index.js", 6 | "es2015": "dist/es6m/index.mjs", 7 | "typings": "dist/types/index.d.ts", 8 | "exports": { 9 | ".": { 10 | "types": "./dist/types/index.d.ts", 11 | "import": "./dist/es6m/index.mjs", 12 | "require": "./dist/es6c/index.js" 13 | }, 14 | "./mikro-orm": { 15 | "types": "./dist/types/lib/mikro-orm.d.ts", 16 | "import": "./dist/es6m/lib/mikro-orm.mjs", 17 | "require": "./dist/es6c/lib/mikro-orm.js" 18 | }, 19 | "./objection": { 20 | "types": "./dist/types/lib/objection.d.ts", 21 | "import": "./dist/es6m/lib/objection.mjs", 22 | "require": "./dist/es6c/lib/objection.js" 23 | }, 24 | "./sequelize": { 25 | "types": "./dist/types/lib/sequelize.d.ts", 26 | "import": "./dist/es6m/lib/sequelize.mjs", 27 | "require": "./dist/es6c/lib/sequelize.js" 28 | }, 29 | "./typeorm": { 30 | "types": "./dist/types/lib/typeorm.d.ts", 31 | "import": "./dist/es6m/lib/typeorm.mjs", 32 | "require": "./dist/es6c/lib/typeorm.js" 33 | } 34 | }, 35 | "scripts": { 36 | "build.types": "tsc", 37 | "build": "npm run build.sql && npm run build.objection && npm run build.sequelize && npm run build.mikro-orm && npm run build.typeorm", 38 | "prebuild": "rm -rf dist/* && npm run build.types", 39 | "build.sql": "BUILD_TYPES=es6m,es6c rollup -c ../../rollup.config.js -e @ucast/core", 40 | "build.objection": "npm run build.sql -- -i src/lib/objection.ts -e objection -e ../index", 41 | "build.sequelize": "npm run build.sql -- -i src/lib/sequelize.ts -e sequelize -e ../index", 42 | "build.mikro-orm": "npm run build.sql -- -i src/lib/mikro-orm.ts -e mikro-orm -e ../index", 43 | "build.typeorm": "npm run build.sql -- -i src/lib/typeorm.ts -e typeorm -e ../index", 44 | "lint": "eslint --ext .js,.ts src/ spec/", 45 | "test": "mocha -r ts-node/register --exclude spec/mikro-orm.spec.ts spec/*", 46 | "coverage": "nyc -n src npm run test && nyc report --reporter=lcov", 47 | "prerelease": "npm run lint && npm test && npm run build", 48 | "release": "semantic-release -e ../../semantic-release.js" 49 | }, 50 | "repository": { 51 | "type": "git", 52 | "url": "git+https://github.com/stalniy/ucast.git" 53 | }, 54 | "publishConfig": { 55 | "access": "public" 56 | }, 57 | "files": [ 58 | "dist", 59 | "NOTICE", 60 | "*.d.ts", 61 | "objection", 62 | "mikro-orm", 63 | "sequelize", 64 | "typeorm" 65 | ], 66 | "keywords": [ 67 | "sql", 68 | "conditions", 69 | "query", 70 | "builder", 71 | "ast" 72 | ], 73 | "author": "Sergii Stotskyi ", 74 | "license": "Apache-2.0", 75 | "bugs": { 76 | "url": "https://github.com/stalniy/ucast/issues" 77 | }, 78 | "homepage": "https://github.com/stalniy/ucast#readme", 79 | "devDependencies": { 80 | "@babel/core": "^7.10.2", 81 | "@babel/plugin-proposal-class-properties": "^7.10.4", 82 | "@babel/plugin-proposal-object-rest-spread": "^7.10.4", 83 | "@babel/plugin-transform-typescript": "^7.10.1", 84 | "@babel/preset-env": "^7.10.2", 85 | "@mikro-orm/core": "^6.5.2", 86 | "@rollup/plugin-babel": "^5.0.3", 87 | "@rollup/plugin-node-resolve": "^8.0.1", 88 | "@semantic-release/changelog": "^5.0.1", 89 | "@semantic-release/git": "^9.0.0", 90 | "@semantic-release/github": "^7.0.7", 91 | "@semantic-release/npm": "^7.0.5", 92 | "@types/bluebird": "^3.5.32", 93 | "@types/chai": "^4.2.11", 94 | "@types/chai-spies": "^1.0.1", 95 | "@types/mocha": "^7.0.2", 96 | "@types/node": "^24.3.1", 97 | "@types/validator": "^13.1.0", 98 | "chai": "^4.2.0", 99 | "chai-spies": "^1.0.0", 100 | "knex": "^3.1.0", 101 | "mikro-orm": "^3.6.15", 102 | "mocha": "^8.0.1", 103 | "nyc": "^15.1.0", 104 | "objection": "^3.1.5", 105 | "reflect-metadata": "^0.2.2", 106 | "rollup": "^2.15.0", 107 | "rollup-plugin-terser": "^6.1.0", 108 | "semantic-release": "^17.4.7", 109 | "sequelize": "6.37.7", 110 | "sqlite3": "^5.1.7", 111 | "ts-node": "^10.9.2", 112 | "typeorm": "^0.3.26", 113 | "typescript": "^5.9.2" 114 | }, 115 | "peerDependencies": { 116 | "mikro-orm": "^3.0.0", 117 | "objection": "^2.0.0", 118 | "sequelize": "^5.0.0 || ^6.0.0", 119 | "typeorm": "^0.2.0" 120 | }, 121 | "peerDependenciesMeta": { 122 | "objection": { 123 | "optional": true 124 | }, 125 | "sequelize": { 126 | "optional": true 127 | }, 128 | "mikro-orm": { 129 | "optional": true 130 | }, 131 | "typeorm": { 132 | "optional": true 133 | } 134 | }, 135 | "dependencies": { 136 | "@ucast/core": "workspace:*" 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /packages/js/README.md: -------------------------------------------------------------------------------- 1 | # UCAST JavaScript 2 | 3 | [![@ucast/js NPM version](https://badge.fury.io/js/%40ucast%2Fjs.svg)](https://badge.fury.io/js/%40ucast%2Fjs) 4 | [![](https://img.shields.io/npm/dm/%40ucast%2Fjs.svg)](https://www.npmjs.com/package/%40ucast%2Fjs) 5 | [![UCAST join the chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/stalniy-ucast/community) 6 | 7 | This package is a part of [ucast] ecosystem. It provides interpreter that can execute conditions AST in JavaScript against any JavaScript object. 8 | 9 | [ucast]: https://github.com/stalniy/ucast 10 | 11 | ## Installation 12 | 13 | ```sh 14 | npm i @ucast/js 15 | # or 16 | yarn add @ucast/js 17 | # or 18 | pnpm add @ucast/js 19 | ``` 20 | 21 | ## Getting Started 22 | 23 | ### Interpret conditions AST 24 | 25 | First of all, you need AST to interpret it. For the sake of an example, we will create it manually: 26 | 27 | ```js 28 | import { CompoundCondition, FieldCondition } from '@ucast/core'; 29 | import { interpret } from '@ucast/js'; 30 | 31 | // x > 5 && y < 10 32 | const condition = new CompoundCondition('and', [ 33 | new FieldCondition('gt', 'x', 5), 34 | new FieldCondition('lt', 'y', 10), 35 | ]); 36 | 37 | interpret(condition, { x: 2, y: 1 }); // false 38 | interpret(condition, { x: 6, y: 7 }); // true 39 | ``` 40 | 41 | The default `interpret` function: 42 | 43 | * supports the next operators, implemented according to [MongoDB query language](https://docs.mongodb.com/manual/reference/operator/query/): 44 | 45 | * `eq`, `ne` 46 | * `lt`, `lte` 47 | * `gt`, `gte` 48 | * `within` (the same as `in` but `in` is a reserved word in JavaScript), `nin` 49 | * `all` 50 | * `regex` 51 | * `or`, `nor`, `and`, `not` 52 | * `exists` 53 | * `size` 54 | * `mod` 55 | * `where`, 56 | * `elemMatch` 57 | 58 | * supports dot notation to access nested object property values in conditions: 59 | 60 | ```js 61 | const condition = new FieldCondition('eq', 'address.street', 'some street'); 62 | interpret(condition, { address: { street: 'another street' } }); // false 63 | ``` 64 | 65 | * compare values by strict equality, so variables that reference objects are equal only if they are references to the same object: 66 | 67 | ```js 68 | const address = { street: 'test' }; 69 | const condition = new FieldCondition('eq', 'address', address); 70 | 71 | interpret(condition, { address }) // true 72 | interpret(condition, { address: { street: 'test' } }) // false, objects are compared by strict equality 73 | ``` 74 | 75 | 76 | ### Custom interpreter 77 | 78 | Sometimes you may want to reduce (or restrict) amount of supported operators (e.g., to utilize tree-shaking and reduce bundle size). To do this you can create a custom interpreter manually: 79 | 80 | ```js 81 | import { FieldCondition } from '@ucast/core'; 82 | import { createJsInterpreter, eq, lt, gt } from '@ucast/js'; 83 | 84 | // supports only $eq, $lt and $gt operators 85 | const interpret = createJsInterpreter({ eq, lt, gt }); 86 | const condition = new FieldCondition('in', 'x', [1, 2]); 87 | 88 | interpret(condition, { x: 1 }) // throws Error, `$in` is not supported 89 | ``` 90 | 91 | ### Custom object matching 92 | 93 | You can also provide a custom `get` or `compare` function. So, you can implement custom logic to get object's property or to compare values. `compare` is used everywhere equality or comparison is required (e.g., in `$in`, `$lt`, `$gt`). This function must return `1` if `a > b`, `-1` if `a < b` and `0` if `a === b`. 94 | 95 | Let's enhance our interpreter to support deep object comparison using [lodash]: 96 | 97 | ```js 98 | import isEqual from 'lodash/isEqual'; 99 | import { createJsInterpreter, allInterpreters, compare } from '@ucast/js'; 100 | 101 | const interpret = createJsInterpreter(allInterpreters, { 102 | compare(a, b) { 103 | if (typeof a === typeof b && typeof a === 'object' && isEqual(a, b)) { 104 | return 0; 105 | } 106 | 107 | return compare(a, b); 108 | } 109 | }); 110 | const condition = new FieldCondition('eq', 'x', { active: true }); 111 | 112 | interpret(condition, { x: { active: true } }); // true 113 | ``` 114 | 115 | ### Custom Operator Interpreter 116 | 117 | Any operator is just a function that accepts 3 parameters and returns boolean result. To see how to implement this function let's create `$type` interpreter that checks object property type using `typeof` operator: 118 | 119 | ```js 120 | import { createJsInterpreter } from '@ucast/js'; 121 | 122 | function type(condition, object, { get }) { 123 | return typeof get(object, condition.field) === condition.value; 124 | } 125 | 126 | const interpret = createJsInterpreter({ type }); 127 | const condition = new FieldCondition('type', 'x', 'number'); 128 | 129 | interpret(condition, { x: 1 }); // true 130 | ``` 131 | 132 | **Pay attention** that object property is got by using `get` function. Make sure that you always use `get` function in custom operators to get object's property value, otherwise your operator will not support dot notation. 133 | 134 | ## Want to help? 135 | 136 | Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for [contributing] 137 | 138 | ## License 139 | 140 | [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 141 | 142 | [contributing]: https://github.com/stalniy/ucast/blob/master/CONTRIBUTING.md 143 | -------------------------------------------------------------------------------- /packages/mongo/src/instructions.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CompoundCondition, 3 | FieldCondition, 4 | NamedInstruction, 5 | CompoundInstruction, 6 | FieldInstruction, 7 | DocumentInstruction, 8 | Comparable, 9 | ITSELF, 10 | NULL_CONDITION, 11 | FieldParsingContext, 12 | optimizedCompoundCondition, 13 | ObjectQueryFieldParsingContext, 14 | } from '@ucast/core'; 15 | import { MongoQuery } from './types'; 16 | 17 | function ensureIsArray(instruction: NamedInstruction, value: unknown) { 18 | if (!Array.isArray(value)) { 19 | throw new Error(`"${instruction.name}" expects value to be an array`); 20 | } 21 | } 22 | 23 | function ensureIsNonEmptyArray(instruction: NamedInstruction, value: unknown[]) { 24 | ensureIsArray(instruction, value); 25 | 26 | if (!value.length) { 27 | throw new Error(`"${instruction.name}" expects to have at least one element in array`); 28 | } 29 | } 30 | 31 | function ensureIsComparable(instruction: NamedInstruction, value: string | number | Date) { 32 | const isComparable = typeof value === 'string' || typeof value === 'number' || value instanceof Date; 33 | 34 | if (!isComparable) { 35 | throw new Error(`"${instruction.name}" expects value to be comparable (i.e., string, number or date)`); 36 | } 37 | } 38 | 39 | const ensureIs = (type: string) => (instruction: NamedInstruction, value: unknown) => { 40 | if (typeof value !== type) { // eslint-disable-line valid-typeof 41 | throw new Error(`"${instruction.name}" expects value to be a "${type}"`); 42 | } 43 | }; 44 | 45 | export const $and: CompoundInstruction[]> = { 46 | type: 'compound', 47 | validate: ensureIsNonEmptyArray, 48 | parse(instruction, queries, { parse }) { 49 | const conditions = queries.map(query => parse(query)); 50 | return optimizedCompoundCondition(instruction.name, conditions); 51 | } 52 | }; 53 | export const $or = $and; 54 | export const $nor: CompoundInstruction[]> = { 55 | type: 'compound', 56 | validate: ensureIsNonEmptyArray, 57 | }; 58 | 59 | export const $not: FieldInstruction | RegExp> = { 60 | type: 'field', 61 | validate(instruction, value) { 62 | const isValid = value && (value instanceof RegExp || value.constructor === Object); 63 | 64 | if (!isValid) { 65 | throw new Error(`"${instruction.name}" expects to receive either regular expression or object of field operators`); 66 | } 67 | }, 68 | parse(instruction, value, context) { 69 | const condition = value instanceof RegExp 70 | ? new FieldCondition('regex' as typeof instruction.name, context.field, value) 71 | : context.parse(value, context); 72 | 73 | return new CompoundCondition(instruction.name, [condition]); 74 | }, 75 | }; 76 | export const $elemMatch: FieldInstruction, ObjectQueryFieldParsingContext> = { 77 | type: 'field', 78 | validate(instruction, value) { 79 | if (!value || value.constructor !== Object) { 80 | throw new Error(`"${instruction.name}" expects to receive an object with nested query or field level operators`); 81 | } 82 | }, 83 | parse(instruction, value, { parse, field, hasOperators }) { 84 | const condition = hasOperators(value) ? parse(value, { field: ITSELF }) : parse(value); 85 | return new FieldCondition(instruction.name, field, condition); 86 | } 87 | }; 88 | 89 | export const $size: FieldInstruction = { 90 | type: 'field', 91 | validate: ensureIs('number') 92 | }; 93 | export const $in: FieldInstruction = { 94 | type: 'field', 95 | validate: ensureIsArray, 96 | }; 97 | export const $nin = $in; 98 | export const $all = $in; 99 | export const $mod: FieldInstruction<[number, number]> = { 100 | type: 'field', 101 | validate(instruction, value) { 102 | if (!Array.isArray(value) || value.length !== 2) { 103 | throw new Error(`"${instruction.name}" expects an array with 2 numeric elements`); 104 | } 105 | } 106 | }; 107 | 108 | export const $exists: FieldInstruction = { 109 | type: 'field', 110 | validate: ensureIs('boolean'), 111 | }; 112 | 113 | export const $gte: FieldInstruction = { 114 | type: 'field', 115 | validate: ensureIsComparable 116 | }; 117 | export const $gt = $gte; 118 | export const $lt = $gt; 119 | export const $lte = $gt; 120 | 121 | export const $eq: FieldInstruction = { 122 | type: 'field', 123 | }; 124 | export const $ne = $eq; 125 | 126 | export interface RegExpFieldContext extends FieldParsingContext { 127 | query: { 128 | $options?: string 129 | } 130 | } 131 | 132 | export const $regex: FieldInstruction = { 133 | type: 'field', 134 | validate(instruction, value) { 135 | if (!(value instanceof RegExp) && typeof value !== 'string') { 136 | throw new Error(`"${instruction.name}" expects value to be a regular expression or a string that represents regular expression`); 137 | } 138 | }, 139 | parse(instruction, rawValue, context) { 140 | const value = typeof rawValue === 'string' 141 | ? new RegExp(rawValue, context.query.$options || '') 142 | : rawValue; 143 | return new FieldCondition(instruction.name, context.field, value); 144 | } 145 | }; 146 | export const $options: FieldInstruction = { 147 | type: 'field', 148 | parse: () => NULL_CONDITION, 149 | }; 150 | 151 | export const $where: DocumentInstruction<() => boolean> = { 152 | type: 'document', 153 | validate: ensureIs('function'), 154 | }; 155 | -------------------------------------------------------------------------------- /packages/mongo2js/README.md: -------------------------------------------------------------------------------- 1 | # UCAST Mongo Query to JavaScript Translator 2 | 3 | [![@ucast/mongo NPM version](https://badge.fury.io/js/%40ucast%2Fmongo2js.svg)](https://badge.fury.io/js/%40ucast%2Fmongo2js) 4 | [![](https://img.shields.io/npm/dm/%40ucast%2Fmongo2js.svg)](https://www.npmjs.com/package/%40ucast%2Fmongo2js) 5 | [![UCAST join the chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/stalniy-ucast/community) 6 | 7 | This package is a part of [ucast] ecosystem. It combines [@ucast/mongo] and [@ucast/js] into a package that allows to evaluate [MongoDB query](https://docs.mongodb.com/manual/reference/operator/query/) conditions in JavaScript runtime. 8 | 9 | [ucast]: https://github.com/stalniy/ucast 10 | [@ucast/mongo]: https://github.com/stalniy/ucast/tree/master/packages/mongo 11 | [@ucast/js]: https://github.com/stalniy/ucast/tree/master/packages/js 12 | 13 | ## Installation 14 | 15 | ```sh 16 | npm i @ucast/mongo2js 17 | # or 18 | yarn add @ucast/mongo2js 19 | # or 20 | pnpm add @ucast/mongo2js 21 | ``` 22 | 23 | ## Getting Started 24 | 25 | To check that POJO can be matched by Mongo Query: 26 | 27 | ```js 28 | import { guard } from '@ucast/mongo2js'; 29 | 30 | const test = guard({ 31 | lastName: 'Doe', 32 | age: { $gt: 18 } 33 | }); 34 | 35 | console.log(test({ 36 | firstName: 'John', 37 | lastName: 'Doe', 38 | age: 19 39 | })); // true 40 | ``` 41 | 42 | You can also get access to parsed Mongo Query AST: 43 | 44 | ```js 45 | console.log(test.ast); /* 46 | { 47 | operator: 'and', 48 | value: [ 49 | { operator: 'eq', field: 'lastName', value: 'Doe' }, 50 | { operator: 'gt', field: 'age', value: 18 } 51 | ] 52 | } 53 | */ 54 | ``` 55 | 56 | ### Testing primitives 57 | 58 | For cases, when you need to test primitive elements, you can use `squire` function: 59 | 60 | ```js 61 | import { squire } from '@ucast/mongo2js'; 62 | 63 | const test = squire({ 64 | $lt: 10, 65 | $gt: 18 66 | }); 67 | 68 | test(11) // true 69 | test(9) // false 70 | ``` 71 | 72 | ### Custom Operator 73 | 74 | In order to implement a custom operator, you need to create a [custom parsing instruction for `MongoQueryParser`](https://github.com/stalniy/ucast/tree/master/packages/mongo#custom-operator) and [custom `JsInterpreter`](https://github.com/stalniy/ucast/tree/master/packages/js#custom-operator-interpreter) to interpret this operator in JavaScript runtime. 75 | 76 | This package re-exports all symbols from `@ucast/mongo` and `@ucast/js`, so you don't need to install them separately. For example, to add support for [json-schema](https://json-schema.org/) operator: 77 | 78 | ```ts 79 | import { 80 | createFactory, 81 | DocumentCondition, 82 | ParsingInstruction, 83 | JsInterpreter, 84 | } from '@ucast/mongo2js'; 85 | import Ajv from 'ajv'; 86 | 87 | type JSONSchema = object; 88 | const ajv = new Ajv(); 89 | const $jsonSchema: ParsingInstruction = { 90 | type: 'document', 91 | validate(instruction, value) { 92 | if (!value || typeof value !== 'object') { 93 | throw new Error(`"${instruction.name}" expects to receive an object`) 94 | } 95 | }, 96 | parse(instruction, schema) { 97 | return new DocumentCondition(instruction.name, ajv.compile(schema)); 98 | } 99 | }; 100 | const jsonSchema: JsInterpreter> = ( 101 | condition, 102 | object 103 | ) => condition.value(object) as boolean; 104 | 105 | const customGuard = createFactory({ 106 | $jsonSchema, 107 | }, { 108 | jsonSchema 109 | }); 110 | const test = customGuard({ 111 | $jsonSchema: { 112 | type: 'object', 113 | properties: { 114 | firstName: { type: 'string' }, 115 | lastName: { type: 'string' }, 116 | }, 117 | required: ['firstName', 'lastName'], 118 | } 119 | }); 120 | 121 | console.log(test({ firstName: 'John' })); // false, `lastName` is not defined 122 | ``` 123 | 124 | To create a custom operator which tests primitives (as `squire` does), use the 125 | `forPrimitives` option: 126 | 127 | ```ts 128 | const customSquire = createFactory({ 129 | $custom: { 130 | type: 'field', 131 | } 132 | }, { 133 | custom: (condition, value) => value === (condition.value ? 'on' : 'off') 134 | }, { 135 | forPrimitives: true 136 | }); 137 | const test = customGuard({ $custom: true }); 138 | console.log(test('on')) // true 139 | ``` 140 | 141 | ## TypeScript support 142 | 143 | This package is written in TypeScript and supports type inference for MongoQuery: 144 | 145 | ```ts 146 | import { guard } from '@ucast/mongo2js'; 147 | 148 | interface Person { 149 | firstName: string 150 | lastName: string 151 | age: number 152 | } 153 | 154 | const test = guard({ lastName: 'Doe' }); 155 | ``` 156 | 157 | You can also use dot notation to set conditions on deeply nested fields: 158 | 159 | ```ts 160 | import { guard } from '@ucast/mongo2js'; 161 | 162 | interface Person { 163 | firstName: string 164 | lastName: string 165 | age: number 166 | address: { 167 | city: string 168 | country: string 169 | } 170 | } 171 | 172 | type ExtendedPerson = Person & { 173 | 'address.city': Person['address']['city'] 174 | } 175 | 176 | const test = guard({ lastName: 'Doe' }); 177 | ``` 178 | 179 | ## Want to help? 180 | 181 | Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for [contributing] 182 | 183 | ## License 184 | 185 | [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 186 | 187 | [contributing]: https://github.com/stalniy/ucast/blob/master/CONTRIBUTING.md 188 | -------------------------------------------------------------------------------- /packages/mongo/README.md: -------------------------------------------------------------------------------- 1 | # UCAST Mongo 2 | 3 | [![@ucast/mongo NPM version](https://badge.fury.io/js/%40ucast%2Fmongo.svg)](https://badge.fury.io/js/%40ucast%2Fmongo) 4 | [![](https://img.shields.io/npm/dm/%40ucast%2Fmongo.svg)](https://www.npmjs.com/package/%40ucast%2Fmongo) 5 | [![UCAST join the chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/stalniy-ucast/community) 6 | 7 | This package is a part of [ucast] ecosystem. It provides a parser that can parse [MongoDB query](https://docs.mongodb.com/manual/reference/operator/query/) into conditions AST. 8 | 9 | [ucast]: https://github.com/stalniy/ucast 10 | 11 | ## Installation 12 | 13 | ```sh 14 | npm i @ucast/mongo 15 | # or 16 | yarn add @ucast/mongo 17 | # or 18 | pnpm add @ucast/mongo 19 | ``` 20 | 21 | ## Getting Started 22 | 23 | To parse MongoDB query into conditions AST, you need to create a `MongoQueryParser` instance: 24 | 25 | ```js 26 | import { MongoQueryParser, allParsingInstructions } from '@ucast/mongo'; 27 | 28 | const parser = new MongoQueryParser(allParsingInstructions); 29 | const ast = parser.parse({ 30 | id: 1, 31 | active: true 32 | }); 33 | ``` 34 | 35 | To create a parser you need to pass in it parsing instruction. Parsing instruction is an object that defines how a particular operator should be parsed. There are 3 types of `ParsingInstruction`, one for each AST node type: 36 | 37 | * `field` represents an instruction for an operator which operates in a field context only. For example, operators `$eq`, `$lt`, `$not`, `$regex` 38 | * `compound` represents an instruction for an operator that aggregates nested queries. For example, operators `$and`, `$or`, `$nor` 39 | * `document` represents an instruction for an operator which operates in a document context only. For example, `$where` or `$jsonSchema` 40 | 41 | It's important to understand that it's not required that parsing instruction with type `field` should be parsed into `FieldCondition`. It can be parsed into `CompoundCondition` as it's done for `$not` operator. 42 | 43 | ### Parsing instruction 44 | 45 | A parsing instruction is an object of 3 fields: 46 | 47 | ```ts 48 | const parsingInstruction = { 49 | type: 'field' | 'document' | 'compound', 50 | validate?(instruction, value) { // optional 51 | // throw exception if something is wrong 52 | }, 53 | parse?(instruction, schema, context) { // optional 54 | /* 55 | * custom logic to parse operator, 56 | * returns FieldCondition | DocumentCondition | CompoundCondition 57 | */ 58 | } 59 | } 60 | ``` 61 | 62 | ### Optimization logic 63 | 64 | Some operators like `$and` and `$or` optimize their parsing logic, so if one of that operators contain a single condition it will be resolved to that condition without additional wrapping. They also recursively collapse conditions from nested operators with the same name. Let's see an example to understand what this means: 65 | 66 | ```js 67 | const ast = parser.parse({ 68 | a: 1 69 | $and: [ 70 | { b: 2 }, 71 | { c: 3 } 72 | ] 73 | }); 74 | console.dir(ast, { depth: null }) 75 | /* 76 | CompoundCondition { 77 | operator: "and", 78 | value: [ 79 | FieldCondition { operator: "eq", field: "a", value: 1 }, 80 | FieldCondition { operator: "eq", field: "b", value: 2 }, 81 | FieldCondition { operator: "eq", field: "c", value: 3 }, 82 | ] 83 | } 84 | */ 85 | ``` 86 | 87 | This optimization logic helps to speed up interpreter's execution time, instead of going deeply over tree-like structure we have a plain structure of all conditions under a single compound condition. 88 | 89 | **Pay attention**: parser removes `$` prefix from operator names 90 | 91 | ### Custom Operator 92 | 93 | In order for an operator to be parsed, it needs to define a parsing instruction. Let's implement a custom instruction which checks that object corresponds to a particular [json schema](https://json-schema.org/). 94 | 95 | First of all, we need to understand on which level this operator operates (field or document). In this case, `$jsonSchema` clearly operates on document level. It doesn't contain nested MongoDB queries, so it's not a `compound` instruction. So, we are left only with `document` one. 96 | 97 | To test that document corresponds to provided json schema, we use [ajv](https://ajv.js.org/) but it's also possible to use a library of your preference. 98 | 99 | ```js 100 | // operators/jsonSchema.js 101 | import { DocumentInstruction, DocumentCondition } from '@ucast/core'; 102 | import Ajv from 'ajv'; 103 | 104 | export const $jsonSchema: DocumentInstruction = { 105 | type: 'document', 106 | validate(instruction, value) { 107 | if (!value || typeof value !== 'object') { 108 | throw new Error(`"${instruction.name}" expects to receive an object`) 109 | } 110 | }, 111 | parse(instruction, schema) { 112 | const ajv = new Ajv(); 113 | return new DocumentCondition(instruction.name, ajv.compile(schema)); 114 | } 115 | }; 116 | ``` 117 | 118 | In order to use this operator, we need to pass this instruction into `MongoQueryParser` constructor: 119 | 120 | ```js 121 | import { MongoQueryParser, allParsingInstructions } from '@ucast/core'; 122 | import { $jsonSchema } from './operators/jsonSchema'; 123 | 124 | const parser = new MongoQueryParser({ 125 | ...allParsingInstructions, 126 | $jsonSchema 127 | }); 128 | const ast = parser.parse({ 129 | $jsonSchema: { 130 | type: 'object', 131 | properties: { 132 | firstName: { type: 'string' }, 133 | lastName: { type: 'string' }, 134 | }, 135 | additionalProperties: false, 136 | } 137 | }); 138 | 139 | console.dir(ast, { depth: null }); 140 | /* 141 | DocumentCondition { operator: "jsonSchema", value: [Function: validate] } 142 | */ 143 | ``` 144 | 145 | The only thing which is left is to implement a corresponding JavaScript interpreter: 146 | 147 | ```js 148 | function jsonSchema(condition, object) { // interpreter 149 | return condition.value(object); 150 | } 151 | ``` 152 | 153 | ## Want to help? 154 | 155 | Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for [contributing] 156 | 157 | ## License 158 | 159 | [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 160 | 161 | [contributing]: https://github.com/stalniy/ucast/blob/master/CONTRIBUTING.md 162 | -------------------------------------------------------------------------------- /packages/core/src/parsers/ObjectQueryParser.ts: -------------------------------------------------------------------------------- 1 | import { Condition } from '../Condition'; 2 | import { 3 | NamedInstruction, 4 | ParsingInstruction, 5 | FieldParsingContext, 6 | ParsingContext, 7 | } from '../types'; 8 | import { buildAnd } from '../builder'; 9 | import { defaultInstructionParsers } from './defaultInstructionParsers'; 10 | import { 11 | identity, 12 | hasOperators, 13 | object, 14 | pushIfNonNullCondition, 15 | objectKeysSkipIgnore, 16 | } from '../utils'; 17 | 18 | export type FieldQueryOperators = { 19 | [K in keyof T]: T[K] extends {} ? T[K] : never 20 | }[keyof T]; 21 | 22 | type ParsingInstructions = Record; 23 | 24 | export interface QueryOptions { 25 | operatorToConditionName?(name: string): string 26 | defaultOperatorName?: string 27 | fieldContext?: Record 28 | documentContext?: Record 29 | useIgnoreValue?: boolean 30 | mergeFinalConditions?(conditions: Condition[]): Condition 31 | } 32 | 33 | export type ObjectQueryFieldParsingContext = ParsingContext(value: unknown): value is T 36 | }>; 37 | 38 | export class ObjectQueryParser< 39 | T extends Record, 40 | U extends FieldQueryOperators = FieldQueryOperators 41 | > { 42 | private readonly _instructions: ParsingInstructions; 43 | private _fieldInstructionContext: ObjectQueryFieldParsingContext; 44 | private _documentInstructionContext: ParsingContext<{ query: {} }>; 45 | private readonly _options: Required< 46 | Pick 47 | >; 48 | 49 | private readonly _objectKeys: typeof Object.keys; 50 | 51 | constructor(instructions: Record, options: QueryOptions = object()) { 52 | this.parse = this.parse.bind(this); 53 | this._options = { 54 | operatorToConditionName: options.operatorToConditionName || identity, 55 | defaultOperatorName: options.defaultOperatorName || 'eq', 56 | mergeFinalConditions: options.mergeFinalConditions || buildAnd, 57 | }; 58 | this._instructions = Object.keys(instructions).reduce((all, name) => { 59 | all[name] = { name: this._options.operatorToConditionName(name), ...instructions[name] }; 60 | return all; 61 | }, {} as ParsingInstructions); 62 | this._fieldInstructionContext = { 63 | ...options.fieldContext, 64 | field: '', 65 | query: {}, 66 | parse: this.parse, 67 | hasOperators: (value: unknown): value is T => hasOperators( 68 | value, 69 | this._instructions, 70 | options.useIgnoreValue 71 | ), 72 | }; 73 | this._documentInstructionContext = { 74 | ...options.documentContext, 75 | parse: this.parse, 76 | query: {} 77 | }; 78 | this._objectKeys = options.useIgnoreValue ? objectKeysSkipIgnore : Object.keys; 79 | } 80 | 81 | setParse(parse: this['parse']) { 82 | this.parse = parse; 83 | this._fieldInstructionContext.parse = parse; 84 | this._documentInstructionContext.parse = parse; 85 | } 86 | 87 | protected parseField(field: string, operator: string, value: unknown, parentQuery: {}) { 88 | const instruction = this._instructions[operator]; 89 | 90 | if (!instruction) { 91 | throw new Error(`Unsupported operator "${operator}"`); 92 | } 93 | 94 | if (instruction.type !== 'field') { 95 | throw new Error(`Unexpected ${instruction.type} operator "${operator}" at field level`); 96 | } 97 | 98 | this._fieldInstructionContext.field = field; 99 | this._fieldInstructionContext.query = parentQuery; 100 | 101 | return this.parseInstruction(instruction, value, this._fieldInstructionContext); 102 | } 103 | 104 | // eslint-disable-next-line class-methods-use-this 105 | protected parseInstruction( 106 | instruction: NamedInstruction, 107 | value: unknown, 108 | context: ParsingContext<{}> 109 | ) { 110 | if (typeof instruction.validate === 'function') { 111 | instruction.validate(instruction, value); 112 | } 113 | 114 | const parse: typeof instruction.parse = instruction.parse 115 | || defaultInstructionParsers[instruction.type as keyof typeof defaultInstructionParsers]; 116 | return parse(instruction, value, context); 117 | } 118 | 119 | protected parseFieldOperators(field: string, value: U) { 120 | const conditions: Condition[] = []; 121 | const keys = this._objectKeys(value); 122 | 123 | for (let i = 0, length = keys.length; i < length; i++) { 124 | const op = keys[i]; 125 | const instruction = this._instructions[op]; 126 | 127 | if (!instruction) { 128 | throw new Error(`Field query for "${field}" may contain only operators or a plain object as a value`); 129 | } 130 | 131 | const condition = this.parseField(field, op, value[op as keyof U], value); 132 | pushIfNonNullCondition(conditions, condition); 133 | } 134 | 135 | return conditions; 136 | } 137 | 138 | parse(query: Q): Condition { 139 | const conditions = []; 140 | const keys = this._objectKeys(query); 141 | 142 | this._documentInstructionContext.query = query; 143 | 144 | for (let i = 0, length = keys.length; i < length; i++) { 145 | const key = keys[i]; 146 | const value = query[key]; 147 | const instruction = this._instructions[key]; 148 | 149 | if (instruction) { 150 | if (instruction.type !== 'document' && instruction.type !== 'compound') { 151 | throw new Error(`Cannot use parsing instruction for operator "${key}" in "document" context as it is supposed to be used in "${instruction.type}" context`); 152 | } 153 | 154 | pushIfNonNullCondition( 155 | conditions, 156 | this.parseInstruction(instruction, value, this._documentInstructionContext) 157 | ); 158 | } else if (this._fieldInstructionContext.hasOperators(value)) { 159 | conditions.push(...this.parseFieldOperators(key, value)); 160 | } else { 161 | pushIfNonNullCondition( 162 | conditions, 163 | this.parseField(key, this._options.defaultOperatorName, value, query) 164 | ); 165 | } 166 | } 167 | 168 | return this._options.mergeFinalConditions(conditions); 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /packages/mongo/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | ## [2.4.3](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.4.2...@ucast/mongo@2.4.3) (2023-02-15) 6 | 7 | 8 | ### Bug Fixes 9 | 10 | * adds typings to ESM exports in package.json ([1ffb703](https://github.com/stalniy/ucast/commit/1ffb7033a6d70ee4eb5f9d3178bcb4df37da835e)) 11 | * updates metadata in package.json ([2fa89f5](https://github.com/stalniy/ucast/commit/2fa89f573eeb033c657b7c54b4640a856859f766)) 12 | 13 | ## [2.4.2](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.4.1...@ucast/mongo@2.4.2) (2021-07-15) 14 | 15 | 16 | ### Bug Fixes 17 | 18 | * remove type commonjs from package.json to improve webpack compat ([#28](https://github.com/stalniy/ucast/issues/28)) ([6b1ad28](https://github.com/stalniy/ucast/commit/6b1ad289d7b4f9945f08f29efd952069efd6c8c9)) 19 | 20 | ## [2.4.1](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.4.0...@ucast/mongo@2.4.1) (2021-01-10) 21 | 22 | 23 | ### Bug Fixes 24 | 25 | * marks packages as commonjs by default with a separate ESM entry ([a3f4896](https://github.com/stalniy/ucast/commit/a3f48961a93b5951cb92d9954297cd12754d3ff1)) 26 | 27 | ## [2.4.1](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.4.0...@ucast/mongo@2.4.1) (2021-01-10) 28 | 29 | 30 | ### Bug Fixes 31 | 32 | * marks packages as commonjs by default with a separate ESM entry ([a3f4896](https://github.com/stalniy/ucast/commit/a3f48961a93b5951cb92d9954297cd12754d3ff1)) 33 | 34 | # [2.4.0](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.3.3...@ucast/mongo@2.4.0) (2020-11-02) 35 | 36 | 37 | ### Bug Fixes 38 | 39 | * **parser:** prevents mangling of `parseField` and `parseFieldOperators` methods of `ObjectQueryParser` ([3b4734b](https://github.com/stalniy/ucast/commit/3b4734b8ac46514aa46855f169e48708d5a9a4b3)) 40 | 41 | 42 | ### Features 43 | 44 | * **parser:** extracts `ObjectQueryParser` out of `MongoQueryParser` into reusable piece ([38941dd](https://github.com/stalniy/ucast/commit/38941dd003dfb0ac9d9f7c867d49b0bbd0b5e716)) 45 | 46 | ## [2.3.3](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.3.2...@ucast/mongo@2.3.3) (2020-10-17) 47 | 48 | 49 | ### Bug Fixes 50 | 51 | * **parser:** ensure parser removes only `$` sign from instructions name ([7fda14e](https://github.com/stalniy/ucast/commit/7fda14e5b2f0c7a3120c1b4be22099c3aceff410)) 52 | 53 | ## [2.3.2](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.3.1...@ucast/mongo@2.3.2) (2020-10-17) 54 | 55 | 56 | ### Bug Fixes 57 | 58 | * **README:** updates outdated docs ([550a08e](https://github.com/stalniy/ucast/commit/550a08ec1b0d0cd71b9ef432757cbc80aad88965)) 59 | 60 | ## [2.3.1](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.3.0...@ucast/mongo@2.3.1) (2020-08-24) 61 | 62 | 63 | ### Bug Fixes 64 | 65 | * **types:** exports `RegExpFieldContext`, so ts allows to use typeof on object of instructions ([9a4580d](https://github.com/stalniy/ucast/commit/9a4580d054a6988fc41732de96d108ddb55b269f)) 66 | 67 | # [2.3.0](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.2.0...@ucast/mongo@2.3.0) (2020-08-20) 68 | 69 | 70 | ### Features 71 | 72 | * **esm:** adds ESM support via dual loading in package.json for latest Node.js version ([c730f95](https://github.com/stalniy/ucast/commit/c730f9598a4c62589c612403c0ac59ba4aa1600e)), closes [#10](https://github.com/stalniy/ucast/issues/10) 73 | 74 | # [2.2.0](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.1.2...@ucast/mongo@2.2.0) (2020-08-18) 75 | 76 | 77 | ### Features 78 | 79 | * **parser:** adds possibility to set `parse` function ([8a1e388](https://github.com/stalniy/ucast/commit/8a1e388fe1c5722ae322b783101f066d763dfde5)), closes [#9](https://github.com/stalniy/ucast/issues/9) 80 | 81 | ## [2.1.2](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.1.1...@ucast/mongo@2.1.2) (2020-08-13) 82 | 83 | 84 | ### Bug Fixes 85 | 86 | * **parser:** updates @ucast/core and uses `buildAnd` instead of `and` ([154c7a6](https://github.com/stalniy/ucast/commit/154c7a6ff86c3a193592f642416030d0d78ea8ea)) 87 | 88 | ## [2.1.1](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.1.0...@ucast/mongo@2.1.1) (2020-08-13) 89 | 90 | 91 | ### Performance Improvements 92 | 93 | * **parser:** replaces `Object.keys().forEach` with `Object.keys() + for(..)` ([003661d](https://github.com/stalniy/ucast/commit/003661da2170243a6bd95233df397eb7c9c4d70a)) 94 | 95 | # [2.1.0](https://github.com/stalniy/ucast/compare/@ucast/mongo@2.0.0...@ucast/mongo@2.1.0) (2020-08-10) 96 | 97 | 98 | ### Bug Fixes 99 | 100 | * **types:** ensure `MongoQuery` returns proper types and can be used with primitive values ([d138ee5](https://github.com/stalniy/ucast/commit/d138ee565bc54d623a283243dc12fc9c930dd2af)) 101 | 102 | 103 | ### Features 104 | 105 | * **types:** exports CustomOperators type and adds `BuildMongoQuery` type ([5ebff17](https://github.com/stalniy/ucast/commit/5ebff1709a448d8683650b26ffff5b7e472c6ac3)) 106 | 107 | # [2.0.0](https://github.com/stalniy/ucast/compare/@ucast/mongo@1.1.0...@ucast/mongo@2.0.0) (2020-08-08) 108 | 109 | 110 | ### Bug Fixes 111 | 112 | * **docs:** removes `$` sign from README examples ([0dc924a](https://github.com/stalniy/ucast/commit/0dc924af72abfefa41ebeac107f1bc070ad796c7)) 113 | 114 | 115 | ### Code Refactoring 116 | 117 | * **parser:** removes `$` from operator name in resulting AST ([e589a9c](https://github.com/stalniy/ucast/commit/e589a9ce577bc191f48e481fc8aebe5b1164783b)) 118 | 119 | 120 | ### BREAKING CHANGES 121 | 122 | * **parser:** `MongoQueryParser.parse` returns AST with operator names that doesn't have `$` prefix. This was done to make it easier import/re-export parser instructions and operator interpreters from single package 123 | 124 | # [1.1.0](https://github.com/stalniy/ucast/compare/@ucast/mongo@1.0.2...@ucast/mongo@1.1.0) (2020-08-08) 125 | 126 | 127 | ### Features 128 | 129 | * **mongo:** adds built-in `$all` instruction for MongoQueryParser ([6d3f224](https://github.com/stalniy/ucast/commit/6d3f224bcba1ef6b875f992752f08d01116bbf9b)) 130 | 131 | 132 | ### Performance Improvements 133 | 134 | * **build:** adds es6cjs format which works few times faster then umd in node env ([4adba3b](https://github.com/stalniy/ucast/commit/4adba3bbf85afe95abfbcee0e36b5edc9d09396f)) 135 | 136 | ## [1.0.2](https://github.com/stalniy/ucast/compare/@ucast/mongo@1.0.1...@ucast/mongo@1.0.2) (2020-07-23) 137 | 138 | 139 | ### Bug Fixes 140 | 141 | * **license:** changes mistakenly set MIT license to the correct one - Apache 2.0 ([197363c](https://github.com/stalniy/ucast/commit/197363c321392c742d31b7e1e024d88c0499ce73)) 142 | 143 | ## [1.0.1](https://github.com/stalniy/ucast/compare/@ucast/mongo@1.0.0...@ucast/mongo@1.0.1) (2020-07-10) 144 | 145 | 146 | ### Bug Fixes 147 | 148 | * **package:** fixes deps ranges ([c2de9c1](https://github.com/stalniy/ucast/commit/c2de9c1b2d6ad85050f4eeb2635c6cb377200013)), closes [#1](https://github.com/stalniy/ucast/issues/1) 149 | 150 | # 1.0.0 (2020-07-10) 151 | 152 | 153 | ### Features 154 | 155 | * **mongo:** adds basic implementation for mongo parser and js interpreter ([a8f7271](https://github.com/stalniy/ucast/commit/a8f7271fc893491755e5c7fb522ed42be992e7b1)) 156 | * **mongo:** stabilize mongo package ([7d77768](https://github.com/stalniy/ucast/commit/7d7776874be3050026b53ee3b61c3361a89d1b21)) 157 | * **mongo:** updates mongo parser to support ValueParsingInstruction ([b918c34](https://github.com/stalniy/ucast/commit/b918c34224a5b60f3f1aa16197587f279b0e3e3a)) 158 | 159 | 160 | ### Reverts 161 | 162 | * **package:** reverts root package.json to fix CI ([277deb5](https://github.com/stalniy/ucast/commit/277deb561bc2a74a2c98170608805ded57802d7d)) 163 | -------------------------------------------------------------------------------- /packages/core/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | ## [1.10.2](https://github.com/stalniy/ucast/compare/@ucast/core@1.10.1...@ucast/core@1.10.2) (2023-02-15) 6 | 7 | 8 | ### Bug Fixes 9 | 10 | * updates metadata in package.json ([2fa89f5](https://github.com/stalniy/ucast/commit/2fa89f573eeb033c657b7c54b4640a856859f766)) 11 | 12 | ## [1.10.2](https://github.com/stalniy/ucast/compare/@ucast/core@1.10.1...@ucast/core@1.10.2) (2023-02-15) 13 | 14 | 15 | ### Bug Fixes 16 | 17 | * updates metadata in package.json ([2fa89f5](https://github.com/stalniy/ucast/commit/2fa89f573eeb033c657b7c54b4640a856859f766)) 18 | 19 | ## [1.10.1](https://github.com/stalniy/ucast/compare/@ucast/core@1.10.0...@ucast/core@1.10.1) (2021-07-15) 20 | 21 | 22 | ### Bug Fixes 23 | 24 | * remove type commonjs from package.json to improve webpack compat ([#28](https://github.com/stalniy/ucast/issues/28)) ([6b1ad28](https://github.com/stalniy/ucast/commit/6b1ad289d7b4f9945f08f29efd952069efd6c8c9)) 25 | 26 | # [1.10.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.9.0...@ucast/core@1.10.0) (2021-03-26) 27 | 28 | 29 | ### Features 30 | 31 | * **parser:** adds support for `ignoreValue` at parser level ([49f8f3a](https://github.com/stalniy/ucast/commit/49f8f3a7221b718326ae125868f0ed24b9c93528)) 32 | 33 | # [1.9.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.8.2...@ucast/core@1.9.0) (2021-03-25) 34 | 35 | 36 | ### Features 37 | 38 | * **parser:** moves `parseInstruction` under `ObjectQueryParser`. Skips `NULL_CONDITION` for all other operators and cases ([bec352e](https://github.com/stalniy/ucast/commit/bec352e3b98447da0d2b704b76446964025c34c9)) 39 | 40 | ## [1.8.2](https://github.com/stalniy/ucast/compare/@ucast/core@1.8.1...@ucast/core@1.8.2) (2021-01-10) 41 | 42 | 43 | ### Bug Fixes 44 | 45 | * **ast:** makes `_notes` to be non-enumerable on `Condition` ([57acee9](https://github.com/stalniy/ucast/commit/57acee91f0bd3c4eaa859461f026f6f6bd159d7b)) 46 | 47 | ## [1.8.2](https://github.com/stalniy/ucast/compare/@ucast/core@1.8.1...@ucast/core@1.8.2) (2021-01-10) 48 | 49 | 50 | ### Bug Fixes 51 | 52 | * **ast:** makes `_notes` to be non-enumerable on `Condition` ([57acee9](https://github.com/stalniy/ucast/commit/57acee91f0bd3c4eaa859461f026f6f6bd159d7b)) 53 | 54 | ## [1.8.1](https://github.com/stalniy/ucast/compare/@ucast/core@1.8.0...@ucast/core@1.8.1) (2021-01-10) 55 | 56 | 57 | ### Bug Fixes 58 | 59 | * marks packages as commonjs by default with a separate ESM entry ([a3f4896](https://github.com/stalniy/ucast/commit/a3f48961a93b5951cb92d9954297cd12754d3ff1)) 60 | 61 | # [1.8.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.7.0...@ucast/core@1.8.0) (2020-12-02) 62 | 63 | 64 | ### Features 65 | 66 | * **condition:** adds possibility to associate notes with parsed condition ([4468773](https://github.com/stalniy/ucast/commit/4468773fcd156feba2fa5f9b6d45d36d56edad20)) 67 | * **interpreter:** adds possibility to customize interpreter name detection ([39b0bc5](https://github.com/stalniy/ucast/commit/39b0bc52015ef794fb6d7360082a378ec2b9bdfe)) 68 | 69 | # [1.7.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.6.1...@ucast/core@1.7.0) (2020-11-23) 70 | 71 | 72 | ### Features 73 | 74 | * **parser:** adds possibility to pass additional field and document level context ([5f32321](https://github.com/stalniy/ucast/commit/5f323219fd960ad764546182b8b54899830de389)) 75 | 76 | ## [1.6.1](https://github.com/stalniy/ucast/compare/@ucast/core@1.6.0...@ucast/core@1.6.1) (2020-11-02) 77 | 78 | 79 | ### Bug Fixes 80 | 81 | * **parser:** prevents mangling of `parseField` and `parseFieldOperators` methods of `ObjectQueryParser` ([3b4734b](https://github.com/stalniy/ucast/commit/3b4734b8ac46514aa46855f169e48708d5a9a4b3)) 82 | 83 | # [1.6.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.5.0...@ucast/core@1.6.0) (2020-11-02) 84 | 85 | 86 | ### Features 87 | 88 | * **parser:** extracts `ObjectQueryParser` out of `MongoQueryParser` into reusable piece ([38941dd](https://github.com/stalniy/ucast/commit/38941dd003dfb0ac9d9f7c867d49b0bbd0b5e716)) 89 | 90 | # [1.5.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.4.1...@ucast/core@1.5.0) (2020-08-20) 91 | 92 | 93 | ### Features 94 | 95 | * **esm:** adds ESM support via dual loading in package.json for latest Node.js version ([c730f95](https://github.com/stalniy/ucast/commit/c730f9598a4c62589c612403c0ac59ba4aa1600e)), closes [#10](https://github.com/stalniy/ucast/issues/10) 96 | 97 | ## [1.4.1](https://github.com/stalniy/ucast/compare/@ucast/core@1.4.0...@ucast/core@1.4.1) (2020-08-13) 98 | 99 | 100 | ### Bug Fixes 101 | 102 | * **builder:** renames condition builder methods as they very likely to conflict with interpreter ([575efc9](https://github.com/stalniy/ucast/commit/575efc9fbe55e8bf235423a365abed5147e6dd39)) 103 | 104 | # [1.4.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.3.0...@ucast/core@1.4.0) (2020-08-13) 105 | 106 | 107 | ### Features 108 | 109 | * **core:** exposes `optimizedCompoundCondition` and `and` and `or` helpers to construct optimized compound conditions ([2ae5584](https://github.com/stalniy/ucast/commit/2ae5584a4a382a1431656880f1ba201664b95e30)) 110 | 111 | # [1.3.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.2.1...@ucast/core@1.3.0) (2020-08-11) 112 | 113 | 114 | ### Features 115 | 116 | * **intepreter:** adds possibility to specify amount of arguments used in interpreter ([e4ddcbd](https://github.com/stalniy/ucast/commit/e4ddcbd6c0602bd3be2befdfcd51ced37cebd158)) 117 | 118 | ## [1.2.1](https://github.com/stalniy/ucast/compare/@ucast/core@1.2.0...@ucast/core@1.2.1) (2020-08-11) 119 | 120 | 121 | ### Bug Fixes 122 | 123 | * **translator:** prevents passing rest parameters from translator to parser ([83c6a56](https://github.com/stalniy/ucast/commit/83c6a56b4ecc66879af0de8deb62da7966080a56)) 124 | 125 | # [1.2.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.1.0...@ucast/core@1.2.0) (2020-08-08) 126 | 127 | 128 | ### Features 129 | 130 | * **condition:** adds generic type to `Condition` interface ([a3f2961](https://github.com/stalniy/ucast/commit/a3f2961879e5bc20ee6379516ed7f0c3d58bd525)) 131 | 132 | # [1.1.0](https://github.com/stalniy/ucast/compare/@ucast/core@1.0.2...@ucast/core@1.1.0) (2020-08-08) 133 | 134 | 135 | ### Features 136 | 137 | * **translator:** adds `ast` property to translate function ([814e874](https://github.com/stalniy/ucast/commit/814e87419a0162f8ef5210d497477d2da08e456a)) 138 | 139 | 140 | ### Performance Improvements 141 | 142 | * **build:** adds es6cjs format which works few times faster then umd in node env ([4adba3b](https://github.com/stalniy/ucast/commit/4adba3bbf85afe95abfbcee0e36b5edc9d09396f)) 143 | 144 | ## [1.0.2](https://github.com/stalniy/ucast/compare/@ucast/core@1.0.1...@ucast/core@1.0.2) (2020-07-23) 145 | 146 | 147 | ### Bug Fixes 148 | 149 | * **license:** changes mistakenly set MIT license to the correct one - Apache 2.0 ([197363c](https://github.com/stalniy/ucast/commit/197363c321392c742d31b7e1e024d88c0499ce73)) 150 | 151 | ## [1.0.1](https://github.com/stalniy/ucast/compare/@ucast/core@1.0.0...@ucast/core@1.0.1) (2020-07-10) 152 | 153 | 154 | ### Bug Fixes 155 | 156 | * **release:** adds build, test and lint prerelease step ([683a532](https://github.com/stalniy/ucast/commit/683a5327b6adb10fcd640ee60fc9479d7036cafc)) 157 | 158 | # 1.0.0 (2020-07-10) 159 | 160 | 161 | ### Features 162 | 163 | * **core:** implements core helpers ([94c5a59](https://github.com/stalniy/ucast/commit/94c5a595fb32941dc0101dd0f468feeafc92329c)) 164 | * **mongo:** stabilize mongo package ([7d77768](https://github.com/stalniy/ucast/commit/7d7776874be3050026b53ee3b61c3361a89d1b21)) 165 | 166 | 167 | ### Reverts 168 | 169 | * **package:** reverts root package.json to fix CI ([277deb5](https://github.com/stalniy/ucast/commit/277deb561bc2a74a2c98170608805ded57802d7d)) 170 | -------------------------------------------------------------------------------- /packages/js/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | ## [3.0.4](https://github.com/stalniy/ucast/compare/@ucast/js@3.0.3...@ucast/js@3.0.4) (2024-01-31) 6 | 7 | 8 | ### Bug Fixes 9 | 10 | * ensure "exists" js interpreter returns value depends on parent field existance for nested fields ([ec1c7d6](https://github.com/stalniy/ucast/commit/ec1c7d6a82bee22dd5c26779f92ff2b5aaf2efb5)) 11 | 12 | ## [3.0.4](https://github.com/stalniy/ucast/compare/@ucast/js@3.0.3...@ucast/js@3.0.4) (2024-01-31) 13 | 14 | 15 | ### Bug Fixes 16 | 17 | * ensure "exists" js interpreter returns value depends on parent field existance for nested fields ([ec1c7d6](https://github.com/stalniy/ucast/commit/ec1c7d6a82bee22dd5c26779f92ff2b5aaf2efb5)) 18 | 19 | ## [3.0.3](https://github.com/stalniy/ucast/compare/@ucast/js@3.0.2...@ucast/js@3.0.3) (2023-02-15) 20 | 21 | 22 | ### Bug Fixes 23 | 24 | * adds typings to ESM exports in package.json ([1ffb703](https://github.com/stalniy/ucast/commit/1ffb7033a6d70ee4eb5f9d3178bcb4df37da835e)) 25 | * updates metadata in package.json ([2fa89f5](https://github.com/stalniy/ucast/commit/2fa89f573eeb033c657b7c54b4640a856859f766)) 26 | 27 | ## [3.0.2](https://github.com/stalniy/ucast/compare/@ucast/js@3.0.1...@ucast/js@3.0.2) (2021-07-15) 28 | 29 | 30 | ### Bug Fixes 31 | 32 | * remove type commonjs from package.json to improve webpack compat ([#28](https://github.com/stalniy/ucast/issues/28)) ([6b1ad28](https://github.com/stalniy/ucast/commit/6b1ad289d7b4f9945f08f29efd952069efd6c8c9)) 33 | 34 | ## [3.0.1](https://github.com/stalniy/ucast/compare/@ucast/js@3.0.0...@ucast/js@3.0.1) (2021-01-10) 35 | 36 | 37 | ### Bug Fixes 38 | 39 | * marks packages as commonjs by default with a separate ESM entry ([a3f4896](https://github.com/stalniy/ucast/commit/a3f48961a93b5951cb92d9954297cd12754d3ff1)) 40 | 41 | # [3.0.0](https://github.com/stalniy/ucast/compare/@ucast/js@2.2.3...@ucast/js@3.0.0) (2020-10-17) 42 | 43 | 44 | ### Bug Fixes 45 | 46 | * **api:** removes deprecated `equal` option for interpreter ([9b086b5](https://github.com/stalniy/ucast/commit/9b086b5b5d81cd1cc4471de90945d6a44a1c35dd)) 47 | 48 | 49 | ### BREAKING CHANGES 50 | 51 | * **api:** removes deprecated `equal` option. It's complitely replaced by `compare` function 52 | 53 | **Before** 54 | 55 | ```js 56 | import { createJsInterpreter, allInterpreters } from '@ucast/js'; 57 | 58 | const interpret = createJsInterpreter(allInterpreters, { 59 | equal: (a, b) => /* custom equality check */ 60 | }); 61 | ``` 62 | 63 | **After** 64 | 65 | ```js 66 | import { createJsInterpreter, allInterpreters, compare } from '@ucast/js'; 67 | 68 | const interpret = createJsInterpreter(allInterpreters, { 69 | compare: (a, b) => { 70 | if (/* custom equality check */) { 71 | return 0; 72 | } 73 | 74 | return compare(a, b); 75 | } 76 | }); 77 | ``` 78 | 79 | ## [2.2.3](https://github.com/stalniy/ucast/compare/@ucast/js@2.2.2...@ucast/js@2.2.3) (2020-10-17) 80 | 81 | 82 | ### Performance Improvements 83 | 84 | * **get:** replaces reduce with for loop in hot function ([e54d86a](https://github.com/stalniy/ucast/commit/e54d86a128b08b3fd936cec67a6ae231c48fa9fc)) 85 | 86 | ## [2.2.2](https://github.com/stalniy/ucast/compare/@ucast/js@2.2.1...@ucast/js@2.2.2) (2020-08-26) 87 | 88 | 89 | ### Bug Fixes 90 | 91 | * **interpreter:** ensure `regexp` correctly works with `null` & `undefined` values ([#14](https://github.com/stalniy/ucast/issues/14)) ([061e5b0](https://github.com/stalniy/ucast/commit/061e5b05474b90998920bb6735add6f676e18989)) 92 | 93 | ## [2.2.1](https://github.com/stalniy/ucast/compare/@ucast/js@2.2.0...@ucast/js@2.2.1) (2020-08-24) 94 | 95 | 96 | ### Bug Fixes 97 | 98 | * **get:** ensure `get` returns flat array for deeply nested object of arrays of object arrays ([#13](https://github.com/stalniy/ucast/issues/13)) ([2efeb91](https://github.com/stalniy/ucast/commit/2efeb91213ee4d39deadb59962684392f94fc8cb)) 99 | 100 | # [2.2.0](https://github.com/stalniy/ucast/compare/@ucast/js@2.1.3...@ucast/js@2.2.0) (2020-08-20) 101 | 102 | 103 | ### Features 104 | 105 | * **esm:** adds ESM support via dual loading in package.json for latest Node.js version ([c730f95](https://github.com/stalniy/ucast/commit/c730f9598a4c62589c612403c0ac59ba4aa1600e)), closes [#10](https://github.com/stalniy/ucast/issues/10) 106 | 107 | ## [2.1.3](https://github.com/stalniy/ucast/compare/@ucast/js@2.1.2...@ucast/js@2.1.3) (2020-08-20) 108 | 109 | 110 | ### Bug Fixes 111 | 112 | * **operator:** ensure `exists` can check existance of array item ([3196ec7](https://github.com/stalniy/ucast/commit/3196ec79e5ef190fe113656fc725cb47ab051c57)) 113 | 114 | ## [2.1.2](https://github.com/stalniy/ucast/compare/@ucast/js@2.1.1...@ucast/js@2.1.2) (2020-08-20) 115 | 116 | 117 | ### Bug Fixes 118 | 119 | * **get:** ensures that `getObjectField` properly works with numeric fields in path ([ee501a2](https://github.com/stalniy/ucast/commit/ee501a23262c2fc4913906ff09386f39883ab98e)) 120 | 121 | ## [2.1.1](https://github.com/stalniy/ucast/compare/@ucast/js@2.1.0...@ucast/js@2.1.1) (2020-08-14) 122 | 123 | 124 | ### Bug Fixes 125 | 126 | * **interpreters:** ensure field level interpreters work with array values as well ([32e38ef](https://github.com/stalniy/ucast/commit/32e38efb9d4dea632f6c927243f6e6b96d57b69b)), closes [#7](https://github.com/stalniy/ucast/issues/7) 127 | 128 | # [2.1.0](https://github.com/stalniy/ucast/compare/@ucast/js@2.0.1...@ucast/js@2.1.0) (2020-08-11) 129 | 130 | 131 | ### Features 132 | 133 | * **comparing:** adds `compare` option to interpreter ([576d128](https://github.com/stalniy/ucast/commit/576d128a92d554e9e6a1508667a2f159908613c6)) 134 | 135 | ## [2.0.1](https://github.com/stalniy/ucast/compare/@ucast/js@2.0.0...@ucast/js@2.0.1) (2020-08-08) 136 | 137 | 138 | ### Bug Fixes 139 | 140 | * **docs:** removes `$` sign from README ([1a7e96b](https://github.com/stalniy/ucast/commit/1a7e96b0e7bd29d7de5fe236863e472e28b9e119)) 141 | 142 | # [2.0.0](https://github.com/stalniy/ucast/compare/@ucast/js@1.0.2...@ucast/js@2.0.0) (2020-08-08) 143 | 144 | 145 | ### Code Refactoring 146 | 147 | * **interpreters:** removes `$` prefix from names of operator interpreters ([04ea7ac](https://github.com/stalniy/ucast/commit/04ea7ac60a6aba4598b4fa27e6decb615e69a29d)) 148 | 149 | 150 | ### Performance Improvements 151 | 152 | * **build:** adds es6cjs format which works few times faster then umd in node env ([4adba3b](https://github.com/stalniy/ucast/commit/4adba3bbf85afe95abfbcee0e36b5edc9d09396f)) 153 | 154 | 155 | ### BREAKING CHANGES 156 | 157 | * **interpreters:** removes `$` prefix from names of operator interpreters. Also renames `$in` to `within` because `in` is a reserved word in JS. This ensures we can safely import/re-export symbols from this package and other parsers/interpreters inside/from single file: 158 | 159 | **Before**: 160 | 161 | ```js 162 | import { $in, $and } from '@ucast/js' 163 | ``` 164 | 165 | **After**: 166 | 167 | ```js 168 | import { within, and } from '@ucast/js' 169 | ``` 170 | 171 | ## [1.0.2](https://github.com/stalniy/ucast/compare/@ucast/js@1.0.1...@ucast/js@1.0.2) (2020-07-23) 172 | 173 | 174 | ### Bug Fixes 175 | 176 | * **license:** changes mistakenly set MIT license to the correct one - Apache 2.0 ([197363c](https://github.com/stalniy/ucast/commit/197363c321392c742d31b7e1e024d88c0499ce73)) 177 | 178 | ## [1.0.1](https://github.com/stalniy/ucast/compare/@ucast/js@1.0.0...@ucast/js@1.0.1) (2020-07-10) 179 | 180 | 181 | ### Bug Fixes 182 | 183 | * **package:** fixes deps ranges ([c2de9c1](https://github.com/stalniy/ucast/commit/c2de9c1b2d6ad85050f4eeb2635c6cb377200013)), closes [#1](https://github.com/stalniy/ucast/issues/1) 184 | 185 | ## [1.0.1](https://github.com/stalniy/ucast/compare/@ucast/js@1.0.0...@ucast/js@1.0.1) (2020-07-10) 186 | 187 | 188 | ### Bug Fixes 189 | 190 | * **package:** fixes deps ranges ([c2de9c1](https://github.com/stalniy/ucast/commit/c2de9c1b2d6ad85050f4eeb2635c6cb377200013)), closes [#1](https://github.com/stalniy/ucast/issues/1) 191 | 192 | # 1.0.0 (2020-07-10) 193 | 194 | 195 | ### Features 196 | 197 | * **mongo:** stabilize mongo package ([7d77768](https://github.com/stalniy/ucast/commit/7d7776874be3050026b53ee3b61c3361a89d1b21)) 198 | * **mongo:** updates mongo parser to support ValueParsingInstruction ([b918c34](https://github.com/stalniy/ucast/commit/b918c34224a5b60f3f1aa16197587f279b0e3e3a)) 199 | 200 | 201 | ### Reverts 202 | 203 | * **package:** reverts root package.json to fix CI ([277deb5](https://github.com/stalniy/ucast/commit/277deb561bc2a74a2c98170608805ded57802d7d)) 204 | -------------------------------------------------------------------------------- /packages/sql/README.md: -------------------------------------------------------------------------------- 1 | # UCAST SQL 2 | 3 | [![@ucast/sql NPM version](https://badge.fury.io/js/%40ucast%2Fsql.svg)](https://badge.fury.io/js/%40ucast%2Fsql) 4 | [![](https://img.shields.io/npm/dm/%40ucast%2Fsql.svg)](https://www.npmjs.com/package/%40ucast%2Fsql) 5 | 6 | This package is a part of [ucast] ecosystem. It provides an interpreter that can translates ucast conditions into [SQL query](https://en.wikipedia.org/wiki/SQL). 7 | 8 | [ucast]: https://github.com/stalniy/ucast 9 | 10 | ## Installation 11 | 12 | ```sh 13 | npm i @ucast/sql 14 | # or 15 | yarn add @ucast/sql 16 | # or 17 | pnpm add @ucast/sql 18 | ``` 19 | 20 | ## Getting Started 21 | 22 | Latest code is in `alpha` branch and in the latest [npm install @ucast/sql@alpha](https://www.npmjs.com/package/@ucast/sql/v/1.0.0-alpha.12) 23 | 24 | ### Interpret conditions AST 25 | 26 | In order to interpret something, we need 2 things: interpreter and AST. It's really easy to create interpreter just pick operators you want to use or pass all of them: 27 | 28 | ```js 29 | import { 30 | createSqlInterpreter, 31 | eq, 32 | lt, 33 | lte, 34 | allInterpreters 35 | } from '@ucast/sql'; 36 | 37 | const interpret = createSqlInterpreter({ eq, lt, lte }); 38 | // or 39 | const interpret = createSqlInterpreter(allInterpreters); 40 | ``` 41 | 42 | `interpret` is a function that takes up to 3 parameters: 43 | 44 | 1. `Condition`, condition to interpret 45 | 2. `options`, SQL dialect specific options that tells how to escape field, create placeholders and join related tables. `@ucast/sql` provides options for the most popular SQL dialects. 46 | 3. `targetQuery`, optional, this is the parameter that `@ucast/sql` passes as the 2nd one to `joinRelation` function. This is useful when integrating with ORMs and their query builders. 47 | 48 | For the sake of an example, we will create AST manually using `Condition` from `@ucast/core`: 49 | 50 | ```js 51 | import { CompoundCondition, FieldCondition } from '@ucast/core'; 52 | 53 | // x > 5 && y < 10 54 | const condition = new CompoundCondition('and', [ 55 | new FieldCondition('gt', 'x', 5), 56 | new FieldCondition('lt', 'y', 10), 57 | ]); 58 | ``` 59 | 60 | Now, we can combine these 2 together to get SQL condition: 61 | 62 | ```js 63 | import { CompoundCondition, FieldCondition } from '@ucast/core'; 64 | import { createSqlInterpreter, allInterpreters, pg } from '@ucast/sql'; 65 | 66 | // x > 5 && y < 10 67 | const condition = new CompoundCondition('and', [ 68 | new FieldCondition('gt', 'x', 5), 69 | new FieldCondition('lt', 'y', 10), 70 | ]); 71 | const interpret = createSqlInterpreter(allInterpreters); 72 | 73 | const [sql, replacements] = interpret(condition, { 74 | ...pg, 75 | joinRelation: () => false 76 | }) 77 | 78 | console.log(sql) // ("x" > $1 and "y < $2) 79 | console.log(replacements) // [5, 10] 80 | ``` 81 | 82 | ### Conditions on related table 83 | 84 | Interpreter automatically detects fields with dot (`.`) inside and interprets them as fields of a relation. It's possible to automatically inner join table using `options.joinRelation` function. That function accepts 2 parameters: relation name and targetQuery (3rd argument of `interpret` function). For example: 85 | 86 | ```js 87 | const condition = new FieldCondition('eq', 'address.street', 'some street'); 88 | const relations = { address: '"address"."id" = "address_id"' }; 89 | const [sql, params, joins] = interpret(condition, { 90 | ...pg, 91 | joinRelation: relationName => relations.hasOwnProperty(relationName) 92 | }); 93 | 94 | console.log(sql) // "address"."street" = $1 95 | console.log(params) // ['some street'] 96 | console.log(joins) // ['address'] 97 | ``` 98 | 99 | ### Custom interpreter 100 | 101 | Sometimes you may want to add custom operator or restrict supported operators. To do this, just pass desired operators manually: 102 | 103 | ```js 104 | import { createSqlInterpreter, eq, lt, gt, pg } from '@ucast/sql'; 105 | 106 | const interpret = createSqlInterpreter({ eq, lt, gt }); 107 | const condition = new FieldCondition('eq', 'x', true); 108 | 109 | interpret(condition, pg); 110 | ``` 111 | 112 | To add a custom operator, all you need to do is to create a function that applies `Condition` to instance of `Query` object. Let's create an operator, that adds condition on `publishedAt` field: 113 | 114 | ```ts 115 | import { DocumentCondition } from '@ucast/core'; 116 | import { 117 | SqlOperator, 118 | createSqlInterpreter, 119 | allInterpreters, 120 | pg, 121 | } from '@ucast/sql'; 122 | 123 | const isActive: SqlOperator> = (node, query) => { 124 | const operator = node.value ? '>=' : '<'; 125 | return query.where('publishedAt', operator, new Date()); 126 | }; 127 | const interpret = createSqlInterpreter({ 128 | ...allInterpreters, 129 | isActive, 130 | }); 131 | const condition = new DocumentCondition('isActive', true); 132 | const [sql, params] = interpret(condition, pg); 133 | 134 | console.log(sql) // "publishedAt" >= $1 135 | console.log(params) // [new Date()] 136 | ``` 137 | 138 | ## Integrations 139 | 140 | This library provides sub-modules that allows quickly integrate SQL interpreter with popular ORMs: 141 | 142 | ### [Sequelize](https://sequelize.org/) 143 | 144 | ```js 145 | import { interpret } from '@ucast/sql/sequelize'; 146 | import { CompoundCondition, FieldCondition } from '@ucast/core'; 147 | import { Model, Sequelize, DataTypes } from 'sequelize'; 148 | 149 | const sequelize = new Sequelize('sqlite::memory:'); 150 | 151 | class User extends Model {} 152 | 153 | User.init({ 154 | name: { type: DataTypes.STRING }, 155 | blocked: { type: DataTypes.BOOLEAN }, 156 | lastLoggedIn: { type: DataTypes.DATETIME }, 157 | }); 158 | 159 | const condition = new CompoundCondition('and', [ 160 | new FieldCondition('eq', 'blocked', false), 161 | new FieldCondition('lt', 'lastLoggedIn', Date.now() - 24 * 3600 * 1000), 162 | ]); 163 | 164 | // { 165 | // include: [], 166 | // where: literal('(`blocked` = 0 and lastLoggedIn < 1597594415354)') 167 | // } 168 | const query = interpret(condition, User) 169 | ``` 170 | 171 | ### [Objection.js](https://vincit.github.io/objection.js/) 172 | 173 | ```js 174 | import { interpret } from '@ucast/sql/objection'; 175 | import { CompoundCondition, FieldCondition } from '@ucast/core'; 176 | import { Model } from 'objection'; 177 | import Knex from 'knex'; 178 | 179 | Model.knex(Knex({ client: 'pg' })); 180 | 181 | class User extends Model {} 182 | 183 | const condition = new CompoundCondition('and', [ 184 | new FieldCondition('eq', 'blocked', false), 185 | new FieldCondition('lt', 'lastLoggedIn', Date.now() - 24 * 3600 * 1000), 186 | ]); 187 | 188 | // the next code produces: 189 | // User.query() 190 | // .where('blocked', false) 191 | // .where('lastLoggedIn', Date.now() - 24 * 3600 * 1000) 192 | const query = interpret(condition, User.query()) 193 | ``` 194 | 195 | ### [MikroORM](https://mikro-orm.io/) 196 | 197 | ```js 198 | import { interpret } from '@ucast/sql/mikro-orm'; 199 | import { CompoundCondition, FieldCondition } from '@ucast/core'; 200 | import { MikroORM, Entity, PrimaryKey, Property } from 'mikro-orm'; 201 | 202 | @Entity() 203 | class User { 204 | @PrimaryKey() 205 | id!: number; 206 | 207 | @Property() 208 | blocked: boolean; 209 | 210 | @Property() 211 | name!: string; 212 | 213 | @Property() 214 | lastLoggedIn = new Date(); 215 | } 216 | 217 | const condition = new CompoundCondition('and', [ 218 | new FieldCondition('eq', 'blocked', false), 219 | new FieldCondition('lt', 'lastLoggedIn', Date.now() - 24 * 3600 * 1000), 220 | ]); 221 | 222 | async function main() { 223 | const orm = await MikroORM.init({ 224 | entities: [User], 225 | dbName: ':memory:', 226 | type: 'sqlite', 227 | }); 228 | 229 | // the next code produces: 230 | // orm.em.createQueryBuilder(User) 231 | // .where('blocked = ?', [false]) 232 | // .andWhere('lastLoggedIn = ?', [Date.now() - 24 * 3600 * 1000]) 233 | const qb = interpret(condition, orm.em.createQueryBuilder(User)); 234 | } 235 | 236 | main().catch(console.error); 237 | ``` 238 | 239 | ### [TypeORM](https://typeorm.io/) 240 | 241 | ```js 242 | import { interpret } from '@ucast/sql/typeorm'; 243 | import { CompoundCondition, FieldCondition } from '@ucast/core'; 244 | import { 245 | Entity, 246 | PrimaryGeneratedColumn, 247 | Column, 248 | createConnection 249 | } from 'typeorm'; 250 | 251 | @Entity() 252 | class User { 253 | @PrimaryGeneratedColumn() 254 | id!: number; 255 | 256 | @Column() 257 | blocked: boolean; 258 | 259 | @Column() 260 | name!: string; 261 | 262 | @Column() 263 | lastLoggedIn = new Date(); 264 | } 265 | 266 | const condition = new CompoundCondition('and', [ 267 | new FieldCondition('eq', 'blocked', false), 268 | new FieldCondition('lt', 'lastLoggedIn', Date.now() - 24 * 3600 * 1000), 269 | ]); 270 | 271 | async function main() { 272 | const conn = await createConnection({ 273 | type: 'sqlite', 274 | database: ':memory:', 275 | entities: [User] 276 | }); 277 | 278 | // the next code produces: 279 | // conn.createQueryBuilder(User, 'u') 280 | // .where('blocked = ?', [false]) 281 | // .andWhere('lastLoggedIn = ?', [Date.now() - 24 * 3600 * 1000]) 282 | const qb = interpret(condition, conn.createQueryBuilder(User, 'u')); 283 | } 284 | 285 | main().catch(console.error); 286 | ``` 287 | 288 | ## TypeScript Support 289 | 290 | Written in TypeScript and supports type inference for supported ORMs. 291 | 292 | ## Want to help? 293 | 294 | Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for [contributing] 295 | 296 | ## License 297 | 298 | [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 299 | 300 | [contributing]: https://github.com/stalniy/ucast/blob/master/CONTRIBUTING.md 301 | -------------------------------------------------------------------------------- /packages/core/spec/ObjectQueryParser.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect, spy } from './specHelper' 2 | import { 3 | FieldCondition, 4 | CompoundCondition, 5 | DocumentCondition, 6 | ObjectQueryParser, 7 | defaultInstructionParsers, 8 | ObjectQueryFieldParsingContext, 9 | ignoreValue 10 | } from '../src' 11 | 12 | describe('ObjectQueryParser', () => { 13 | const eq = { type: 'field' } 14 | const and = { type: 'compound' } 15 | const where = { type: 'document' } 16 | 17 | it('throws when trying to use unknown operator', () => { 18 | const parser = new ObjectQueryParser({}) 19 | expect(() => parser.parse({ field: { unknown: true } })).to.throw(/Unsupported operator/) 20 | }) 21 | 22 | it('throws when trying to use field level operator at root level', () => { 23 | const parser = new ObjectQueryParser({ eq }) 24 | expect(() => parser.parse({ eq: 5 })) 25 | .to.throw(/Cannot use parsing instruction for operator "eq" in "document" context/) 26 | }) 27 | 28 | it('throws when trying to use compound or value operator at field level', () => { 29 | const parser = new ObjectQueryParser({ and, where }) 30 | expect(() => parser.parse({ field: { and: [] } })).to.throw(/Unexpected compound operator/) 31 | expect(() => { 32 | return parser.parse({ field: { where: () => true } }) 33 | }).to.throw(/Unexpected document operator/) 34 | }) 35 | 36 | it('parses object value pairs as "and" of "eq" conditions', () => { 37 | const parser = new ObjectQueryParser({ and, eq }) 38 | const ast = parser.parse({ a: 1, b: 2 }) as CompoundCondition 39 | const conditions = ast.value as FieldCondition[] 40 | 41 | expect(ast).to.be.instanceOf(CompoundCondition) 42 | expect(ast.operator).to.equal('and') 43 | expect(conditions).to.have.length(2) 44 | expect(conditions.every(c => c instanceof FieldCondition && c.operator === 'eq')).to.be.true 45 | }) 46 | 47 | it('passes additional field context details during processing field level operators', () => { 48 | const my = { type: 'field', parse: spy(defaultInstructionParsers.field) } 49 | const parser = new ObjectQueryParser({ my }, { 50 | fieldContext: { check: true } 51 | }) 52 | parser.parse({ field: { my: 1 } }) 53 | const context = spy.calls(my.parse)[0][2] as { check: boolean } 54 | 55 | expect(context.check).to.be.true 56 | }) 57 | 58 | it('passes additional document context details during processing document level and compound operators', () => { 59 | const document = { type: 'document', parse: spy(defaultInstructionParsers.document) } 60 | const compound = { type: 'compound', parse: spy(defaultInstructionParsers.compound) } 61 | const parser = new ObjectQueryParser({ document, compound }, { 62 | documentContext: { check: true } 63 | }) 64 | parser.parse({ document: true, compound: [] }) 65 | const documentContext = spy.calls(document.parse)[0][2] as { check: boolean } 66 | const compoundContext = spy.calls(compound.parse)[0][2] as { check: boolean } 67 | 68 | expect(documentContext.check).to.be.true 69 | expect(compoundContext.check).to.be.true 70 | }) 71 | 72 | describe('when "field" level parsing instruction is specified', () => { 73 | it('parses it to `FieldCondition`', () => { 74 | const my = { type: 'field' } 75 | const parser = new ObjectQueryParser({ my }) 76 | const ast = parser.parse({ field: { my: 1 } }) as FieldCondition 77 | 78 | expect(ast).to.be.instanceOf(FieldCondition) 79 | expect(ast.operator).to.equal('my') 80 | expect(ast.value).to.equal(1) 81 | expect(ast.field).to.equal('field') 82 | }) 83 | 84 | it('uses its "validate" hook to validate operator value', () => { 85 | const my = { type: 'field', validate: spy() } 86 | const parser = new ObjectQueryParser({ my }) 87 | parser.parse({ field: { my: 1 } }) 88 | 89 | expect(my.validate).to.have.been.called.with({ ...my, name: 'my' }, 1) 90 | }) 91 | 92 | it('uses its "parse" hook to customize its parsing', () => { 93 | const my = { type: 'field', parse: spy(defaultInstructionParsers.field) } 94 | const parser = new ObjectQueryParser({ my }) 95 | parser.parse({ field: { my: 1 } }) 96 | const context = spy.calls(my.parse)[0][2] as ObjectQueryFieldParsingContext 97 | 98 | expect(my.parse).to.have.been.called.with({ ...my, name: 'my' }, 1, { 99 | field: 'field', 100 | query: { my: 1 }, 101 | parse: parser.parse, 102 | hasOperators: context.hasOperators 103 | }) 104 | }) 105 | }) 106 | 107 | describe('when "compound" level parsing instruction is specified', () => { 108 | it('parses it to `CompoundCondition`', () => { 109 | const my = { type: 'compound' } 110 | const parser = new ObjectQueryParser({ my }) 111 | const ast = parser.parse({ my: [] }) as CompoundCondition 112 | 113 | expect(ast).to.be.instanceOf(CompoundCondition) 114 | expect(ast.operator).to.equal('my') 115 | expect(ast.value).to.have.length(0) 116 | }) 117 | 118 | it('parses value as nested condition', () => { 119 | const my = { type: 'compound' } 120 | const parser = new ObjectQueryParser({ my, eq }) 121 | const ast = parser.parse({ my: { a: 1 } }) as CompoundCondition 122 | const childAst = ast.value[0] as FieldCondition 123 | 124 | expect(ast.value).to.have.length(1) 125 | expect(childAst).to.be.instanceOf(FieldCondition) 126 | expect(childAst.operator).to.equal('eq') 127 | expect(childAst.value).to.equal(1) 128 | expect(childAst.field).to.equal('a') 129 | }) 130 | 131 | it('uses its "validate" hook to validate operator value', () => { 132 | const my = { type: 'compound', validate: spy() } 133 | const parser = new ObjectQueryParser({ my }) 134 | parser.parse({ my: [] }) 135 | 136 | expect(my.validate).to.have.been.called.with({ ...my, name: 'my' }, []) 137 | }) 138 | 139 | it('uses its "parse" hook to customize its parsing', () => { 140 | const my = { type: 'compound', parse: spy(defaultInstructionParsers.compound) } 141 | const parser = new ObjectQueryParser({ my }) 142 | parser.parse({ my: [] }) 143 | 144 | expect(my.parse).to.have.been.called.with({ ...my, name: 'my' }, [], { 145 | parse: parser.parse, 146 | query: { my: [] }, 147 | }) 148 | }) 149 | }) 150 | 151 | describe('when "document" level parsing instruction is specified', () => { 152 | it('parses it to `DocumentCondition`', () => { 153 | const my = { type: 'document' } 154 | const parser = new ObjectQueryParser({ my }) 155 | const ast = parser.parse({ my: 1 }) as DocumentCondition 156 | 157 | expect(ast).to.be.instanceOf(DocumentCondition) 158 | expect(ast.operator).to.equal('my') 159 | expect(ast.value).to.equal(1) 160 | }) 161 | 162 | it('uses its "validate" hook to validate operator value', () => { 163 | const my = { type: 'document', validate: spy() } 164 | const parser = new ObjectQueryParser({ my }) 165 | parser.parse({ my: 1 }) 166 | 167 | expect(my.validate).to.have.been.called.with({ ...my, name: 'my' }, 1) 168 | }) 169 | 170 | it('uses its "parse" hook to customize its parsing', () => { 171 | const my = { type: 'document', parse: spy(defaultInstructionParsers.document) } 172 | const parser = new ObjectQueryParser({ my }) 173 | parser.parse({ my: 2 }) 174 | 175 | expect(my.parse).to.have.been.called.with({ ...my, name: 'my' }, 2, { 176 | parse: parser.parse, 177 | query: { my: 2 }, 178 | }) 179 | }) 180 | }) 181 | 182 | describe('when "useIgnoreValue" is enabled', () => { 183 | describe('field level operators', () => { 184 | it('ignores properties that equals to `ignoreValue`', () => { 185 | const parser = new ObjectQueryParser({ eq }, { useIgnoreValue: true }) 186 | const result = parser.parse({ id: ignoreValue, name: 'test' }) 187 | 188 | expect(result).to.deep.equal(new FieldCondition('eq', 'name', 'test')) 189 | }) 190 | 191 | it('returns empty "AND" condition if all properties equals to `ignoreValue`', () => { 192 | const parser = new ObjectQueryParser({ eq }, { useIgnoreValue: true }) 193 | const result = parser.parse({ id: ignoreValue, name: ignoreValue }) 194 | 195 | expect(result).to.deep.equal(new CompoundCondition('and', [ 196 | ])) 197 | }) 198 | }) 199 | 200 | describe('multiple field level operators per field', () => { 201 | it('ignores operators that equals to `ignoreValue`', () => { 202 | const parser = new ObjectQueryParser({ eq, ne: eq }, { useIgnoreValue: true }) 203 | const result = parser.parse({ 204 | id: { eq: ignoreValue, ne: 5 }, 205 | name: ignoreValue 206 | }) 207 | 208 | expect(result).to.deep.equal(new FieldCondition('ne', 'id', 5)) 209 | }) 210 | 211 | it('interprets multiple field level operators as equality operator if all properties inside equal `ignoreValue`', () => { 212 | const parser = new ObjectQueryParser({ eq }, { useIgnoreValue: true }) 213 | const result = parser.parse({ id: { eq: ignoreValue } }) 214 | 215 | expect(result).to.deep.equal(new FieldCondition('eq', 'id', { eq: ignoreValue })) 216 | }) 217 | }) 218 | 219 | describe('document level operators', () => { 220 | it('ignores operators that equals to `ignoreValue`', () => { 221 | const parser = new ObjectQueryParser({ and, eq }, { useIgnoreValue: true }) 222 | const result = parser.parse({ and: ignoreValue, id: 5 }) 223 | 224 | expect(result).to.deep.equal(new FieldCondition('eq', 'id', 5)) 225 | }) 226 | 227 | it('interprets single operator as empty "AND" condition if it equals to `ignoreValue`', () => { 228 | const parser = new ObjectQueryParser({ and, eq }, { useIgnoreValue: true }) 229 | const result = parser.parse({ and: ignoreValue }) 230 | 231 | expect(result).to.deep.equal(new CompoundCondition('and', [])) 232 | }) 233 | 234 | it('interprets `ignoreValue` inside compound operator as empty "AND"', () => { 235 | const parser = new ObjectQueryParser({ and, eq }, { useIgnoreValue: true }) 236 | const result = parser.parse({ and: [ignoreValue] }) 237 | 238 | expect(result).to.deep.equal(new CompoundCondition('and', [ 239 | new CompoundCondition('and', []) 240 | ])) 241 | }) 242 | }) 243 | }) 244 | }) 245 | -------------------------------------------------------------------------------- /packages/core/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /packages/js/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | --------------------------------------------------------------------------------