/**
* Generates a simple WHERE clause for TypeORM based on query and fields.
*
* @template T - The entity type.
* @param {string} query - The search query.
* @param {string} fields - A comma-separated list of fields to search in.
* @param {FindOptionsWhere<T>} [defaultWhere={}] - Default WHERE conditions.
* @returns {FindOptionsWhere<T> | FindOptionsWhere<T>[]} The generated WHERE clause(s).
* @example
* const query = 'example';
* const fields = 'name,description';
* const defaultWhereMany = {} as FindManyOptions<MyEntity>['where'];
* const where = genSimpleWhere<MyEntity>(query, fields, defaultWhere);
* console.log(where);
* // Output:
* // { name: ILike("%example%"), description: ILike("%example%") }
*
*/
export const genSimpleWhere = <T>(
query: string,
fields: string,
defaultWhere: FindOptionsWhere<T> = {},
): FindOptionsWhere<T> | FindOptionsWhere<T>[] => {
const clauses = fields
.split(',')
.map((f) => ({ ...defaultWhere, [f.trim()]: ILike(`%${query}%`) }));
return clauses.length === 1 ? clauses[0] : clauses;
};
Associated Context | |
---|---|
Type | Code Snippet ( .ts ) |
Associated Tags | TypeORM Query and Fields FindOptionsWhere Default WHERE conditions Generating where clause ILike function List of fields String manipulation Console log Framework: TypeORM typeorm query builder where clause database typescript javascript search ilike findoptionswhere generic |
💡 Smart Description | This code snippet defines a function called "genSimpleWhere" that generates a simple WHERE clause for typeORM based on the query and fields. It takes in an array of strings, sorts it into separate columns using findOptionsWhere or `defaultWhereGenerates TypeORM WHERE clauses for simple search queries across specified fields, optionally merging with default conditions. |
🔎 Suggested Searches | Generate simple WHERE clause for TypeORM based on query and fields FindManyOptions example in TypeORM where function How to generate a generic WHERE clause with typeORM using QueryAndFields Code snippet for generating an AND clause from the search query or fields Example code for creating a Simple WHERE clause between queries typeorm where clause findoptionswhere ilike query builder typescript |
Related Links | https://www.typescriptlang.org/docs/handbook/generics.html typeorm/typeorm#2173 |
Related People | Andrés Godínez |
Sensitive Information | No Sensitive Information Detected |
Shareable Link | https://user-de183283-7469-43c5-8511-5429d1cdfde1-45htvp2guq-uc.a.run.app/?p=f659408193 |