mongodb $like implementation

Signed-off-by: Andrey Platov <andrey@hardcoreeng.com>
This commit is contained in:
Andrey Platov 2021-10-01 15:33:49 +02:00
parent 7e33fd8906
commit 1d7c296d8a
No known key found for this signature in database
GPG Key ID: C8787EFEB4B64AF0
2 changed files with 20 additions and 4 deletions

View File

@ -19,8 +19,6 @@ import type { Doc } from './classes'
type Predicate = (docs: Doc[]) => Doc[]
type PredicateFactory = (pred: any, propertyKey: string) => Predicate
const likeSymbol = '%'
const predicates: Record<string, PredicateFactory> = {
$in: (o: any, propertyKey: string): Predicate => {
if (!Array.isArray(o)) {
@ -36,7 +34,7 @@ const predicates: Record<string, PredicateFactory> = {
},
$like: (query: string, propertyKey: string): Predicate => {
const searchString = query.split(likeSymbol).join('.*')
const searchString = query.split('%').join('.*')
const regex = RegExp(`^${searchString}$`, 'i')
return (docs: Doc[]): Doc[] => {
const result: Doc[] = []

View File

@ -35,8 +35,26 @@ abstract class MongoAdapterBase extends TxProcessor {
async init (): Promise<void> {}
private translateQuery<T extends Doc> (clazz: Ref<Class<T>>, query: DocumentQuery<T>): Filter<Document> {
const translated: any = {}
for (const key in query) {
const value = (query as any)[key]
if (typeof value === 'object') {
const keys = Object.keys(value)
if (keys[0] === '$like') {
const pattern = value.$like as string
translated[key] = {
$regex: `^${pattern.split('%').join('.*')}$`,
$options: 'i'
}
continue
}
}
translated[key] = value
}
const classes = this.hierarchy.getDescendants(clazz)
return Object.assign({}, query, { _class: { $in: classes } })
translated._class = { $in: classes }
// return Object.assign({}, query, { _class: { $in: classes } })
return translated
}
private async lookup<T extends Doc> (clazz: Ref<Class<T>>, query: DocumentQuery<T>, options: FindOptions<T>): Promise<FindResult<T>> {