|
| 1 | +import { ObjectLiteral } from 'typeorm' |
| 2 | +import { validate } from '../validate' |
| 3 | +import { ApplyFilterParams, QueryFilters } from './types' |
| 4 | + |
| 5 | +export function applyFilter<T extends ObjectLiteral>({ |
| 6 | + query, |
| 7 | + filters, |
| 8 | + model, |
| 9 | + options, |
| 10 | +}: ApplyFilterParams<T>) { |
| 11 | + let filtered: QueryFilters[] = [] |
| 12 | + |
| 13 | + if (Array.isArray(filters)) { |
| 14 | + filtered = filters |
| 15 | + } else { |
| 16 | + filtered = JSON.parse(filters) as QueryFilters[] |
| 17 | + } |
| 18 | + |
| 19 | + if (filtered.length > 0) { |
| 20 | + for (let i = 0; i < filtered.length; i += 1) { |
| 21 | + const item = filtered[i] |
| 22 | + |
| 23 | + const check_uuid = validate.uuid(item.value) |
| 24 | + const check_numeric = validate.number(item.value) |
| 25 | + const check_boolean = validate.boolean(item.value) |
| 26 | + const expect_number_uuid_boolean = !check_numeric && !check_uuid && !check_boolean |
| 27 | + |
| 28 | + const postgres_driver = options?.type === 'postgres' |
| 29 | + const mysql_driver = ['mysql', 'mariadb'].includes(String(options?.type)) |
| 30 | + |
| 31 | + if (check_uuid || check_numeric || check_boolean) { |
| 32 | + query.andWhere(`${model}.${item.id} = :${item.id}`, { |
| 33 | + [`${item.id}`]: `${item.value}`, |
| 34 | + }) |
| 35 | + } |
| 36 | + |
| 37 | + if (mysql_driver && expect_number_uuid_boolean) { |
| 38 | + query.andWhere(`${model}.${item.id} LIKE :${item.id}`, { |
| 39 | + [`${item.id}`]: `%${item.value}%`, |
| 40 | + }) |
| 41 | + } |
| 42 | + |
| 43 | + if (postgres_driver && expect_number_uuid_boolean) { |
| 44 | + query.andWhere(`${model}.${item.id} ILIKE :${item.id}`, { |
| 45 | + [`${item.id}`]: `%${item.value}%`, |
| 46 | + }) |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments