Added contains support for datasource pluses

This commit is contained in:
Mel O'Hagan 2022-07-19 17:25:41 +01:00
parent 9b12dd6b47
commit ed0bd07732
3 changed files with 44 additions and 15 deletions

View File

@ -19,8 +19,8 @@ class QueryBuilder {
empty: {},
notEmpty: {},
oneOf: {},
contains: {},
...base
contains: {} ,
...base,
}
this.limit = 50
this.sortOrder = "ascending"

View File

@ -131,6 +131,9 @@ export interface SearchFilters {
oneOf?: {
[key: string]: any[]
}
contains?: {
[key: string]: any
}
}
export interface SortJson {

View File

@ -142,6 +142,21 @@ class InternalBuilder {
}
}
}
const like = (key: string, value: any) => {
const fnc = allOr ? "orWhere" : "where"
// postgres supports ilike, nothing else does
if (this.client === SqlClients.POSTGRES) {
query = query[fnc](key, "ilike", `%${value}%`)
} else {
const rawFnc = `${fnc}Raw`
// @ts-ignore
query = query[rawFnc](`LOWER(${likeKey(this.client, key)}) LIKE ?`, [
`%${value}%`,
])
}
}
if (!filters) {
return query
}
@ -168,19 +183,7 @@ class InternalBuilder {
})
}
if (filters.fuzzy) {
iterate(filters.fuzzy, (key, value) => {
const fnc = allOr ? "orWhere" : "where"
// postgres supports ilike, nothing else does
if (this.client === SqlClients.POSTGRES) {
query = query[fnc](key, "ilike", `%${value}%`)
} else {
const rawFnc = `${fnc}Raw`
// @ts-ignore
query = query[rawFnc](`LOWER(${likeKey(this.client, key)}) LIKE ?`, [
`%${value}%`,
])
}
})
iterate(filters.fuzzy, like)
}
if (filters.range) {
iterate(filters.range, (key, value) => {
@ -223,6 +226,29 @@ class InternalBuilder {
query = query[fnc](key)
})
}
if (filters.contains) {
const fnc = allOr ? "orWhere" : "where"
const rawFnc = `${fnc}Raw`
if (this.client === SqlClients.POSTGRES) {
iterate(filters.contains, (key: string, value: any) => {
const fieldNames = key.split(/\./g)
const tableName = fieldNames[0]
const columnName = fieldNames[1]
// @ts-ignore
query = query[rawFnc](`"${tableName}"."${columnName}"::jsonb @> '["${value}"]'`)
})
} else if (this.client === SqlClients.MY_SQL) {
iterate(filters.contains, (key: string, value: any) => {
if (typeof value === "string") {
value = `"${value}"`
}
// @ts-ignore
query = query[rawFnc](`JSON_CONTAINS(${key}, '${value}')`)
})
} else {
iterate(filters.contains, like)
}
}
return query
}