|
| 1 | +import { |
| 2 | + filterSchema, |
| 3 | + FilterSchema, |
| 4 | + FilterSchemaOptions, |
| 5 | + SearchFilterInput, |
| 6 | +} from '@tacxou/nestjs_module_restools/search-filter-schema'; |
| 7 | + |
| 8 | +export type FilterGroup = Record<string, unknown>; |
| 9 | + |
| 10 | +/** |
| 11 | + * Filtre au format des clés signées : un groupe de conditions combinées par ET, |
| 12 | + * ou une liste de groupes combinés par OU |
| 13 | + */ |
| 14 | +export type FilterGroups = FilterGroup | FilterGroup[]; |
| 15 | + |
| 16 | +function isPlainRecord(value: unknown): value is Record<string, unknown> { |
| 17 | + return value !== null && typeof value === 'object' && !Array.isArray(value); |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Retourne la liste des groupes OU du filtre, ou null s'il s'agit d'un simple groupe ET. |
| 22 | + * qs transforme les tableaux de plus de 20 éléments en objets indexés (`{ "0": ..., "21": ... }`) : ils sont aussi acceptés. |
| 23 | + */ |
| 24 | +export function extractFilterGroups(filters: unknown): FilterGroup[] | null { |
| 25 | + if (Array.isArray(filters)) { |
| 26 | + if (filters.some((group) => !isPlainRecord(group))) { |
| 27 | + throw new Error('Invalid filters: expected an array of filter groups'); |
| 28 | + } |
| 29 | + return filters; |
| 30 | + } |
| 31 | + |
| 32 | + if (isPlainRecord(filters)) { |
| 33 | + const keys = Object.keys(filters); |
| 34 | + if (keys.length > 0 && keys.every((key) => /^\d+$/.test(key) && isPlainRecord(filters[key]))) { |
| 35 | + return keys.sort((a, b) => Number(a) - Number(b)).map((key) => filters[key] as FilterGroup); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return null; |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Préfixe de négation d'une condition : `!<signe><champ>` (ex: `!^mail` = ne contient pas) |
| 44 | + */ |
| 45 | +export const FILTER_NEGATION_PREFIX = '!'; |
| 46 | + |
| 47 | +/** |
| 48 | + * Inverse une condition Mongo d'un champ : `$not` pour une expression d'opérateurs, `$ne` pour une égalité |
| 49 | + */ |
| 50 | +function negateCondition(condition: unknown): unknown { |
| 51 | + const isOperatorExpression = isPlainRecord(condition) && Object.keys(condition).some((key) => key.startsWith('$')); |
| 52 | + return isOperatorExpression ? { $not: condition } : { $ne: condition }; |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Convertit un groupe de conditions combinées par ET, en gérant la négation `!` de chaque condition. |
| 57 | + * restools ne sait nier que `:`, `#` et `@` : la négation est donc appliquée ici, sur le résultat de la condition positive. |
| 58 | + */ |
| 59 | +function filterGroupSchema(group: FilterGroup, options?: FilterSchemaOptions): FilterSchema { |
| 60 | + const positive: FilterGroup = {}; |
| 61 | + const negated: Record<string, unknown>[] = []; |
| 62 | + |
| 63 | + for (const [key, value] of Object.entries(group)) { |
| 64 | + if (!key.startsWith(FILTER_NEGATION_PREFIX)) { |
| 65 | + positive[key] = value; |
| 66 | + continue; |
| 67 | + } |
| 68 | + |
| 69 | + const condition = filterSchema({ [key.slice(1)]: value } as SearchFilterInput, options); |
| 70 | + for (const [field, fieldCondition] of Object.entries(condition)) { |
| 71 | + negated.push({ [field]: negateCondition(fieldCondition) }); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + const result: Record<string, unknown> = { ...filterSchema(positive as SearchFilterInput, options) }; |
| 76 | + const conflicts: Record<string, unknown>[] = []; |
| 77 | + for (const condition of negated) { |
| 78 | + const [field, fieldCondition] = Object.entries(condition)[0]; |
| 79 | + if (field in result) conflicts.push(condition); |
| 80 | + else result[field] = fieldCondition; |
| 81 | + } |
| 82 | + if (conflicts.length) result.$and = conflicts; |
| 83 | + |
| 84 | + return result as FilterSchema; |
| 85 | +} |
| 86 | + |
| 87 | +/** |
| 88 | + * Extension de `filterSchema` (restools) supportant des groupes de conditions reliés par un OU |
| 89 | + * et la négation de chaque condition. |
| 90 | + * |
| 91 | + * Format accepté : |
| 92 | + * - `{ "<signe><champ>": valeur, ... }` : conditions combinées par ET (format historique) |
| 93 | + * - `[ { ...conditions ET... }, { ... } ]` : (groupe 1) OU (groupe 2) ... |
| 94 | + * (en query : `filters[0][:sn]=x&filters[1][^mail]=/foo/i`) |
| 95 | + * - `{ "!<signe><champ>": valeur }` : négation de la condition (ex: `!^mail` = ne contient pas) |
| 96 | + * |
| 97 | + * Le OU est encapsulé dans un `$and` afin de ne pas entrer en conflit avec le `$or` |
| 98 | + * de la recherche textuelle que les controllers fusionnent au même niveau. |
| 99 | + */ |
| 100 | +export function filterSchemaWithGroups( |
| 101 | + filters: SearchFilterInput | FilterGroups, |
| 102 | + options?: FilterSchemaOptions, |
| 103 | +): FilterSchema { |
| 104 | + const groups = extractFilterGroups(filters); |
| 105 | + if (!groups) { |
| 106 | + return isPlainRecord(filters) |
| 107 | + ? filterGroupSchema(filters, options) |
| 108 | + : filterSchema(filters as SearchFilterInput, options); |
| 109 | + } |
| 110 | + |
| 111 | + const conditions = groups |
| 112 | + .map((group) => filterGroupSchema(group, options)) |
| 113 | + .filter((condition) => Object.keys(condition).length > 0); |
| 114 | + |
| 115 | + if (conditions.length === 0) return {}; |
| 116 | + if (conditions.length === 1) return conditions[0]; |
| 117 | + |
| 118 | + return { $and: [{ $or: conditions }] } as unknown as FilterSchema; |
| 119 | +} |
| 120 | + |
| 121 | +/** |
| 122 | + * Indique si un filtre Mongo issu de `filterSchemaWithGroups` porte une condition sur la clé donnée, |
| 123 | + * à la racine ou dans un groupe `$and` / `$or` |
| 124 | + */ |
| 125 | +export function filterSchemaHasKey(schema: unknown, key: string): boolean { |
| 126 | + if (!isPlainRecord(schema)) return false; |
| 127 | + if (Object.prototype.hasOwnProperty.call(schema, key)) return true; |
| 128 | + |
| 129 | + return ['$and', '$or'].some( |
| 130 | + (operator) => |
| 131 | + Array.isArray(schema[operator]) && schema[operator].some((sub: unknown) => filterSchemaHasKey(sub, key)), |
| 132 | + ); |
| 133 | +} |
0 commit comments