From a60785d563a3b4b6a96703c35f37f9d2bbfdbefc Mon Sep 17 00:00:00 2001 From: rijkvanzanten Date: Wed, 8 Jul 2020 13:15:44 -0400 Subject: [PATCH] Add support for search query param --- src/database/run-ast.ts | 20 +++++++++++++++++++- src/middleware/sanitize-query.ts | 4 ++++ src/types/query.ts | 1 + 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/database/run-ast.ts b/src/database/run-ast.ts index 69dd49584e..eb22174dfc 100644 --- a/src/database/run-ast.ts +++ b/src/database/run-ast.ts @@ -1,6 +1,6 @@ import { AST, NestedCollectionAST } from '../types/ast'; import { uniq } from 'lodash'; -import database from './index'; +import database, { schemaInspector } from './index'; import { Query } from '../types/query'; export default async function runAST(ast: AST, query = ast.query) { @@ -69,6 +69,24 @@ export default async function runAST(ast: AST, query = ast.query) { dbQuery.limit(1).first(); } + if (query.search && ast.type === 'collection') { + const columns = await schemaInspector.columnInfo(ast.name); + + columns + /** @todo Check if this scales between SQL vendors */ + .filter( + (column) => + column.type.toLowerCase().includes('text') || + column.type.toLowerCase().includes('char') + ) + .forEach((column) => { + dbQuery.orWhereRaw( + `LOWER(${column.name}) LIKE '%' || LOWER(?) || '%'`, + query.search + ); + }); + } + let results = await dbQuery; for (const batch of nestedCollections) { diff --git a/src/middleware/sanitize-query.ts b/src/middleware/sanitize-query.ts index f81c07d025..eae5a7dc4a 100644 --- a/src/middleware/sanitize-query.ts +++ b/src/middleware/sanitize-query.ts @@ -51,6 +51,10 @@ const sanitizeQuery: RequestHandler = (req, res, next) => { query.meta = sanitizeMeta(req.query.meta); } + if (req.query.search && typeof req.query.search === 'string') { + query.search = req.query.search; + } + req.sanitizedQuery = query; return next(); }; diff --git a/src/types/query.ts b/src/types/query.ts index 71aee8b8aa..992acdd140 100644 --- a/src/types/query.ts +++ b/src/types/query.ts @@ -9,6 +9,7 @@ export type Query = { page?: number; single?: boolean; meta?: Meta[]; + search?: string; }; export type Sort = {