@starbemtech/star-db-query-builder 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.eslintignore +4 -0
  2. package/.eslintrc.json +32 -0
  3. package/.husky/pre-commit +1 -0
  4. package/.prettierignore +3 -0
  5. package/.prettierrc +5 -0
  6. package/dist/.eslintrc.json +32 -0
  7. package/dist/index.d.ts +2 -0
  8. package/dist/index.js +21 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/src/db/IDatabaseClient.d.ts +5 -0
  11. package/dist/src/db/IDatabaseClient.js +3 -0
  12. package/dist/src/db/IDatabaseClient.js.map +1 -0
  13. package/dist/src/db/initDb.d.ts +6 -0
  14. package/dist/src/db/initDb.js +30 -0
  15. package/dist/src/db/initDb.js.map +1 -0
  16. package/dist/src/db/mysqlClient.d.ts +3 -0
  17. package/dist/src/db/mysqlClient.js +12 -0
  18. package/dist/src/db/mysqlClient.js.map +1 -0
  19. package/dist/src/db/pgClient.d.ts +3 -0
  20. package/dist/src/db/pgClient.js +12 -0
  21. package/dist/src/db/pgClient.js.map +1 -0
  22. package/dist/src/default/genericRepository.d.ts +14 -0
  23. package/dist/src/default/genericRepository.js +97 -0
  24. package/dist/src/default/genericRepository.js.map +1 -0
  25. package/dist/src/default/types.d.ts +35 -0
  26. package/dist/src/default/types.js +3 -0
  27. package/dist/src/default/types.js.map +1 -0
  28. package/dist/src/default/utils.d.ts +8 -0
  29. package/dist/src/default/utils.js +91 -0
  30. package/dist/src/default/utils.js.map +1 -0
  31. package/index.d.ts +42 -0
  32. package/index.ts +5 -0
  33. package/jest.config.ts +199 -0
  34. package/package.json +66 -0
  35. package/src/db/IDatabaseClient.ts +6 -0
  36. package/src/db/initDb.ts +27 -0
  37. package/src/db/mysqlClient.ts +10 -0
  38. package/src/db/pgClient.ts +10 -0
  39. package/src/default/genericRepository.ts +143 -0
  40. package/src/default/types.ts +53 -0
  41. package/src/default/utils.ts +107 -0
package/.eslintignore ADDED
@@ -0,0 +1,4 @@
1
+ # common
2
+ dist/
3
+ build/
4
+ pnpm-lock.yaml
package/.eslintrc.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "env": {
3
+ "es2021": true,
4
+ "node": true
5
+ },
6
+ "extends": [
7
+ "eslint:recommended",
8
+ "prettier",
9
+ "plugin:@typescript-eslint/recommended"
10
+ ],
11
+ "parser": "@typescript-eslint/parser",
12
+ "parserOptions": {
13
+ "ecmaVersion": "latest",
14
+ "sourceType": "module"
15
+ },
16
+ "plugins": [
17
+ "@typescript-eslint",
18
+ "prettier"
19
+ ],
20
+ "rules": {
21
+ "prettier/prettier": "error",
22
+ "@typescript-eslint/explicit-function-return-type": "off",
23
+ "@typescript-eslint/no-explicit-any": "off",
24
+ "@typescript-eslint/explicit-module-boundary-types": "off",
25
+ "@typescript-eslint/no-require-imports": "off",
26
+ "import/prefer-default-export": "off",
27
+ "no-param-reassign": "off",
28
+ "no-console": "off",
29
+ "no-return-assign": "off",
30
+ "array-callback-return": "off"
31
+ }
32
+ }
@@ -0,0 +1 @@
1
+ npm test
@@ -0,0 +1,3 @@
1
+ # Ignore artifacts:
2
+ build
3
+ coverage
package/.prettierrc ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "semi": false,
3
+ "singleQuote": true,
4
+ "trailingComma": "es5"
5
+ }
@@ -0,0 +1,32 @@
1
+ {
2
+ "env": {
3
+ "es2021": true,
4
+ "node": true
5
+ },
6
+ "extends": [
7
+ "eslint:recommended",
8
+ "prettier",
9
+ "plugin:@typescript-eslint/recommended"
10
+ ],
11
+ "parser": "@typescript-eslint/parser",
12
+ "parserOptions": {
13
+ "ecmaVersion": "latest",
14
+ "sourceType": "module"
15
+ },
16
+ "plugins": [
17
+ "@typescript-eslint",
18
+ "prettier"
19
+ ],
20
+ "rules": {
21
+ "prettier/prettier": "error",
22
+ "@typescript-eslint/explicit-function-return-type": "off",
23
+ "@typescript-eslint/no-explicit-any": "off",
24
+ "@typescript-eslint/explicit-module-boundary-types": "off",
25
+ "@typescript-eslint/no-require-imports": "off",
26
+ "import/prefer-default-export": "off",
27
+ "no-param-reassign": "off",
28
+ "no-console": "off",
29
+ "no-return-assign": "off",
30
+ "array-callback-return": "off"
31
+ }
32
+ }
@@ -0,0 +1,2 @@
1
+ export * from './src/db/initDb';
2
+ export * from './src/default/genericRepository';
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ // Configs
18
+ __exportStar(require("./src/db/initDb"), exports);
19
+ // Generic Repository
20
+ __exportStar(require("./src/default/genericRepository"), exports);
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,UAAU;AACV,kDAA+B;AAE/B,qBAAqB;AACrB,kEAA+C"}
@@ -0,0 +1,5 @@
1
+ import { DBClients } from '../default/types';
2
+ export type IDatabaseClient = {
3
+ clientType: DBClients;
4
+ query: <T>(sql: string, params?: any[]) => Promise<T>;
5
+ };
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=IDatabaseClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IDatabaseClient.js","sourceRoot":"","sources":["../../../src/db/IDatabaseClient.ts"],"names":[],"mappings":""}
@@ -0,0 +1,6 @@
1
+ import { IDatabaseClient } from './IDatabaseClient';
2
+ export declare const initDb: (config: {
3
+ type: 'pg' | 'mysql';
4
+ options: any;
5
+ }) => void;
6
+ export declare const getDbClient: () => IDatabaseClient;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDbClient = exports.initDb = void 0;
4
+ const pg_1 = require("pg");
5
+ const promise_1 = require("mysql2/promise");
6
+ const pgClient_1 = require("./pgClient");
7
+ const mysqlClient_1 = require("./mysqlClient");
8
+ let dbClient = null;
9
+ const initDb = (config) => {
10
+ if (config.type === 'pg') {
11
+ const pool = new pg_1.Pool(config.options);
12
+ dbClient = (0, pgClient_1.createPgClient)(pool);
13
+ }
14
+ else if (config.type === 'mysql') {
15
+ const pool = (0, promise_1.createPool)(config.options);
16
+ dbClient = (0, mysqlClient_1.createMysqlClient)(pool);
17
+ }
18
+ else {
19
+ throw new Error('Unsupported database type');
20
+ }
21
+ };
22
+ exports.initDb = initDb;
23
+ const getDbClient = () => {
24
+ if (!dbClient) {
25
+ throw new Error('Database client is not initialized');
26
+ }
27
+ return dbClient;
28
+ };
29
+ exports.getDbClient = getDbClient;
30
+ //# sourceMappingURL=initDb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initDb.js","sourceRoot":"","sources":["../../../src/db/initDb.ts"],"names":[],"mappings":";;;AAAA,2BAAmC;AACnC,4CAA8D;AAC9D,yCAA2C;AAC3C,+CAAiD;AAGjD,IAAI,QAAQ,GAA2B,IAAI,CAAA;AAEpC,MAAM,MAAM,GAAG,CAAC,MAA8C,EAAE,EAAE;IACvE,IAAI,MAAM,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QACzB,MAAM,IAAI,GAAG,IAAI,SAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;QACvC,QAAQ,GAAG,IAAA,yBAAc,EAAC,IAAI,CAAC,CAAA;IACjC,CAAC;SAAM,IAAI,MAAM,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACnC,MAAM,IAAI,GAAG,IAAA,oBAAe,EAAC,MAAM,CAAC,OAAO,CAAC,CAAA;QAC5C,QAAQ,GAAG,IAAA,+BAAiB,EAAC,IAAI,CAAC,CAAA;IACpC,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAA;IAC9C,CAAC;AACH,CAAC,CAAA;AAVY,QAAA,MAAM,UAUlB;AAEM,MAAM,WAAW,GAAG,GAAoB,EAAE;IAC/C,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAA;IACvD,CAAC;IAED,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA;AANY,QAAA,WAAW,eAMvB"}
@@ -0,0 +1,3 @@
1
+ import { Pool } from 'mysql2/promise';
2
+ import { IDatabaseClient } from './IDatabaseClient';
3
+ export declare const createMysqlClient: (pool: Pool) => IDatabaseClient;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createMysqlClient = void 0;
4
+ const createMysqlClient = (pool) => ({
5
+ clientType: 'mysql',
6
+ query: async (sql, params) => {
7
+ const [rows] = await pool.execute(sql, params);
8
+ return rows;
9
+ },
10
+ });
11
+ exports.createMysqlClient = createMysqlClient;
12
+ //# sourceMappingURL=mysqlClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mysqlClient.js","sourceRoot":"","sources":["../../../src/db/mysqlClient.ts"],"names":[],"mappings":";;;AAGO,MAAM,iBAAiB,GAAG,CAAC,IAAU,EAAmB,EAAE,CAAC,CAAC;IACjE,UAAU,EAAE,OAAO;IACnB,KAAK,EAAE,KAAK,EAAK,GAAW,EAAE,MAAc,EAAc,EAAE;QAC1D,MAAM,CAAC,IAAI,CAAC,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;QAC9C,OAAO,IAAoB,CAAA;IAC7B,CAAC;CACF,CAAC,CAAA;AANW,QAAA,iBAAiB,qBAM5B"}
@@ -0,0 +1,3 @@
1
+ import { Pool } from 'pg';
2
+ import { IDatabaseClient } from './IDatabaseClient';
3
+ export declare const createPgClient: (pool: Pool) => IDatabaseClient;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPgClient = void 0;
4
+ const createPgClient = (pool) => ({
5
+ clientType: 'pg',
6
+ query: async (sql, params) => {
7
+ const { rows } = await pool.query(sql, params);
8
+ return rows;
9
+ },
10
+ });
11
+ exports.createPgClient = createPgClient;
12
+ //# sourceMappingURL=pgClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgClient.js","sourceRoot":"","sources":["../../../src/db/pgClient.ts"],"names":[],"mappings":";;;AAGO,MAAM,cAAc,GAAG,CAAC,IAAU,EAAmB,EAAE,CAAC,CAAC;IAC9D,UAAU,EAAE,IAAI;IAChB,KAAK,EAAE,KAAK,EAAK,GAAW,EAAE,MAAc,EAAc,EAAE;QAC1D,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;QAC9C,OAAO,IAAoB,CAAA;IAC7B,CAAC;CACF,CAAC,CAAA;AANW,QAAA,cAAc,kBAMzB"}
@@ -0,0 +1,14 @@
1
+ import { QueryParams } from './types';
2
+ export declare const findFirst: <T>({ tableName, dbClient, select, where, groupBy, orderBy, }: QueryParams) => Promise<T>;
3
+ export declare const findMany: <T>({ tableName, dbClient, select, where, groupBy, orderBy, limit, }: QueryParams) => Promise<T[]>;
4
+ export declare const insert: <T>({ tableName, dbClient, data, returning, }: QueryParams & {
5
+ data: T;
6
+ returning?: string[] | undefined;
7
+ }) => Promise<T | void>;
8
+ export declare const update: <T>({ tableName, dbClient, id, data, returning, }: QueryParams & {
9
+ data: T;
10
+ returning?: string[] | undefined;
11
+ }) => Promise<T | void>;
12
+ export declare const deleteOne: ({ tableName, dbClient, id, permanently, }: QueryParams & {
13
+ permanently?: boolean | undefined;
14
+ }) => Promise<void>;
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteOne = exports.update = exports.insert = exports.findMany = exports.findFirst = void 0;
4
+ const utils_1 = require("./utils");
5
+ const findFirst = async ({ tableName, dbClient, select, where, groupBy, orderBy, }) => {
6
+ if (!tableName)
7
+ throw new Error('Table name is required');
8
+ if (!dbClient)
9
+ throw new Error('DB client is required');
10
+ const fields = (0, utils_1.createSelectFields)(select);
11
+ const [whereClause, params] = (0, utils_1.createWhereClause)(where);
12
+ const orderByClause = (0, utils_1.createOrderByClause)(orderBy);
13
+ const groupByClause = (0, utils_1.createGroupByClause)(groupBy);
14
+ const rows = await dbClient.query(`SELECT ${fields} FROM ${tableName}
15
+ ${whereClause.length > 7 ? whereClause : ''}
16
+ ${groupByClause}
17
+ ${orderByClause}
18
+ `, [params]);
19
+ return rows[0] || null;
20
+ };
21
+ exports.findFirst = findFirst;
22
+ const findMany = async ({ tableName, dbClient, select, where, groupBy, orderBy, limit, }) => {
23
+ if (!tableName)
24
+ throw new Error('Table name is required');
25
+ if (!dbClient)
26
+ throw new Error('DB client is required');
27
+ const fields = (0, utils_1.createSelectFields)(select);
28
+ const [whereClause, params] = (0, utils_1.createWhereClause)(where);
29
+ const orderByClause = (0, utils_1.createOrderByClause)(orderBy);
30
+ const groupByClause = (0, utils_1.createGroupByClause)(groupBy);
31
+ const limitClause = (0, utils_1.createLimitClause)(limit);
32
+ const rows = await dbClient.query(`SELECT ${fields} FROM ${tableName}
33
+ ${whereClause.length > 7 ? whereClause : ''}
34
+ ${groupByClause}
35
+ ${orderByClause}
36
+ ${limitClause}
37
+ `, [params]);
38
+ return rows || [];
39
+ };
40
+ exports.findMany = findMany;
41
+ const insert = async ({ tableName, dbClient, data, returning, }) => {
42
+ if (!tableName)
43
+ throw new Error('Table name is required');
44
+ if (!dbClient)
45
+ throw new Error('DB client is required');
46
+ if (!data)
47
+ throw new Error('Data object is required');
48
+ const keys = Object.keys(data);
49
+ const values = Object.values(data);
50
+ const placeholders = (0, utils_1.generatePlaceholders)(keys, dbClient.clientType);
51
+ let query = `INSERT INTO ${tableName} (${keys.join(', ')}) VALUES (${placeholders})`;
52
+ if (dbClient.clientType === 'pg') {
53
+ if (returning && returning.length > 0) {
54
+ query += ` RETURNING ${(0, utils_1.createSelectFields)(returning)}`;
55
+ }
56
+ }
57
+ const inserted = await dbClient.query(query, values);
58
+ if (dbClient.clientType === 'pg')
59
+ return inserted[0];
60
+ };
61
+ exports.insert = insert;
62
+ const update = async ({ tableName, dbClient, id, data, returning, }) => {
63
+ if (!tableName)
64
+ throw new Error('Table name is required');
65
+ if (!dbClient)
66
+ throw new Error('DB client is required');
67
+ if (!id)
68
+ throw new Error('ID is required');
69
+ if (!data)
70
+ throw new Error('Data object is required');
71
+ const keys = Object.keys(data);
72
+ const values = Object.values(data);
73
+ const setClause = (0, utils_1.generateSetClause)(keys, dbClient.clientType);
74
+ let query = `UPDATE ${tableName} SET ${setClause} WHERE ${id}`;
75
+ if (dbClient.clientType === 'pg') {
76
+ if (returning && returning.length > 0) {
77
+ query += ` RETURNIN ${(0, utils_1.createSelectFields)(returning)}`;
78
+ }
79
+ }
80
+ const updated = await dbClient.query(query, values);
81
+ if (dbClient.clientType === 'pg')
82
+ return updated[0];
83
+ };
84
+ exports.update = update;
85
+ const deleteOne = async ({ tableName, dbClient, id, permanently = false, }) => {
86
+ if (!tableName)
87
+ throw new Error('Table name is required');
88
+ if (!dbClient)
89
+ throw new Error('DB client is required');
90
+ if (!id)
91
+ throw new Error('ID is required');
92
+ await dbClient.query(permanently
93
+ ? `DELETE FROM ${tableName} WHERE id = ${dbClient.clientType === 'pg' ? '$1' : '?'}`
94
+ : `UPDATE ${tableName} SET status = 'deleted' WHERE id = ${dbClient.clientType === 'pg' ? '$1' : '?'}`, [id]);
95
+ };
96
+ exports.deleteOne = deleteOne;
97
+ //# sourceMappingURL=genericRepository.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"genericRepository.js","sourceRoot":"","sources":["../../../src/default/genericRepository.ts"],"names":[],"mappings":";;;AACA,mCAQgB;AAET,MAAM,SAAS,GAAG,KAAK,EAAK,EACjC,SAAS,EACT,QAAQ,EACR,MAAM,EACN,KAAK,EACL,OAAO,EACP,OAAO,GACK,EAAc,EAAE;IAC5B,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;IACzD,IAAI,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAA;IAEvD,MAAM,MAAM,GAAG,IAAA,0BAAkB,EAAC,MAAM,CAAC,CAAA;IACzC,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,GAAG,IAAA,yBAAiB,EAAC,KAAK,CAAC,CAAA;IACtD,MAAM,aAAa,GAAG,IAAA,2BAAmB,EAAC,OAAO,CAAC,CAAA;IAClD,MAAM,aAAa,GAAG,IAAA,2BAAmB,EAAC,OAAO,CAAC,CAAA;IAElD,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,KAAK,CAC/B,UAAU,MAAM,SAAS,SAAS;QAC9B,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;QACzC,aAAa;QACb,aAAa;KAChB,EACD,CAAC,MAAM,CAAC,CACT,CAAA;IAED,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAA;AACxB,CAAC,CAAA;AA1BY,QAAA,SAAS,aA0BrB;AAEM,MAAM,QAAQ,GAAG,KAAK,EAAK,EAChC,SAAS,EACT,QAAQ,EAC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AAC,IAAI,CAAC,CAAC,CAAC,GAAG,EAAE,EACxG,CAAC,EAAE,CAAC,CACL,CAAA;AACH,CAAC,CAAA;AAhBY,QAAA,SAAS,aAgBrB"}
@@ -0,0 +1,35 @@
1
+ import { IDatabaseClient } from '../db/IDatabaseClient';
2
+ export interface QueryExec {
3
+ text: string;
4
+ values?: any[];
5
+ }
6
+ type SimpleValue = string | number | boolean | Date;
7
+ type ConditionOperator = 'AND' | 'OR';
8
+ interface OperatorCondition {
9
+ operator: 'LIKE' | '=' | '>' | '<' | 'IN' | 'BETWEEN' | '!=' | '<=' | '>=' | 'NOT IN' | 'LIKE' | 'NOT LIKE';
10
+ value: SimpleValue | SimpleValue[];
11
+ }
12
+ export type DBClients = 'pg' | 'mysql';
13
+ export interface CompositeCondition {
14
+ type: ConditionOperator;
15
+ conditions: Condition[];
16
+ }
17
+ export type Condition = SimpleValue | OperatorCondition | CompositeCondition;
18
+ export interface Conditions {
19
+ [key: string]: Condition;
20
+ }
21
+ export type OrderBy = {
22
+ field: string;
23
+ direction: 'ASC' | 'DESC';
24
+ }[];
25
+ export interface QueryParams {
26
+ tableName: string;
27
+ dbClient: IDatabaseClient;
28
+ id?: string;
29
+ select?: string[];
30
+ where?: Conditions;
31
+ orderBy?: OrderBy;
32
+ groupBy?: string[];
33
+ limit?: number;
34
+ }
35
+ export {};
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/default/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,8 @@
1
+ import { Conditions, OrderBy, DBClients } from './types';
2
+ export declare const createSelectFields: (fields?: string[]) => string;
3
+ export declare const generatePlaceholders: (keys: any[], clientType: DBClients) => string;
4
+ export declare const generateSetClause: (keys: any[], clientType: DBClients) => string;
5
+ export declare const createWhereClause: (conditions?: Conditions, startIndex?: number) => [string, any[], number];
6
+ export declare const createOrderByClause: (orderBy?: OrderBy) => string;
7
+ export declare const createGroupByClause: (groupBy?: string[]) => string;
8
+ export declare const createLimitClause: (limit?: number) => string;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLimitClause = exports.createGroupByClause = exports.createOrderByClause = exports.createWhereClause = exports.generateSetClause = exports.generatePlaceholders = exports.createSelectFields = void 0;
4
+ const arrayToStringWithQuotes = (items) => {
5
+ const itemsWithQuotes = items.map((item) => `"${item}"`);
6
+ return itemsWithQuotes.join(', ');
7
+ };
8
+ const createSelectFields = (fields) => {
9
+ return fields && fields.length > 0 ? arrayToStringWithQuotes(fields) : '*';
10
+ };
11
+ exports.createSelectFields = createSelectFields;
12
+ const generatePlaceholders = (keys, clientType) => {
13
+ return keys
14
+ .map((_, index) => (clientType === 'pg' ? `$${index + 1}` : '?'))
15
+ .join(', ');
16
+ };
17
+ exports.generatePlaceholders = generatePlaceholders;
18
+ const generateSetClause = (keys, clientType) => {
19
+ return keys
20
+ .map((key, index) => clientType === 'pg' ? `${key} = $${index + 1}` : `${key} = ?`)
21
+ .join(', ');
22
+ };
23
+ exports.generateSetClause = generateSetClause;
24
+ const createWhereClause = (conditions = {}, startIndex = 1) => {
25
+ let index = startIndex;
26
+ const whereParts = [];
27
+ const values = [];
28
+ const processCondition = (key, condition) => {
29
+ if (typeof condition === 'object' && condition !== null) {
30
+ if ('operator' in condition && 'value' in condition) {
31
+ const { operator, value } = condition;
32
+ if (Array.isArray(value)) {
33
+ const placeholders = value.map(() => `$${index++}`).join(', ');
34
+ if (operator === 'BETWEEN') {
35
+ whereParts.push(`"${key}" ${operator} ${placeholders.replace(', ', ' AND ')}`);
36
+ }
37
+ else {
38
+ whereParts.push(`"${key}" ${operator} (${placeholders})`);
39
+ }
40
+ values.push(...value);
41
+ }
42
+ else {
43
+ whereParts.push(`"${key}" ${operator} $${index++}`);
44
+ values.push(value);
45
+ }
46
+ }
47
+ else if ('type' in condition && 'conditions' in condition) {
48
+ const compositeCondition = condition;
49
+ const subWhereParts = [];
50
+ compositeCondition.conditions.forEach((subCondition) => {
51
+ // Recurso: criar uma chave fictícia, pois as condições compostas não necessitam de chave
52
+ index = processCondition('', subCondition);
53
+ });
54
+ whereParts.push(`(${subWhereParts.join(` ${compositeCondition.type} `)})`);
55
+ }
56
+ }
57
+ else if (key) {
58
+ // Condição simples
59
+ whereParts.push(`"${key}" = $${index}`);
60
+ values.push(condition);
61
+ index++;
62
+ }
63
+ return index;
64
+ };
65
+ Object.entries(conditions).forEach(([key, value]) => {
66
+ index = processCondition(key, value);
67
+ });
68
+ const whereClause = whereParts.length > 0 ? ` WHERE ${whereParts.join(' AND ')}` : '';
69
+ return [whereClause, values, index];
70
+ };
71
+ exports.createWhereClause = createWhereClause;
72
+ const createOrderByClause = (orderBy) => {
73
+ if (!orderBy || orderBy.length === 0)
74
+ return '';
75
+ const clause = orderBy.map((o) => `${o.field} ${o.direction}`).join(', ');
76
+ return ` ORDER BY ${clause}`;
77
+ };
78
+ exports.createOrderByClause = createOrderByClause;
79
+ const createGroupByClause = (groupBy) => {
80
+ if (!groupBy || groupBy.length === 0)
81
+ return '';
82
+ return ` GROUP BY ${groupBy.join(', ')}`;
83
+ };
84
+ exports.createGroupByClause = createGroupByClause;
85
+ const createLimitClause = (limit) => {
86
+ if (!limit)
87
+ return '';
88
+ return ` LIMIT ${limit}`;
89
+ };
90
+ exports.createLimitClause = createLimitClause;
91
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/default/utils.ts"],"names":[],"mappings":";;;AAQA,MAAM,uBAAuB,GAAG,CAAC,KAAe,EAAU,EAAE;IAC1D,MAAM,eAAe,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,GAAG,CAAC,CAAA;IACxD,OAAO,eAAe,CAAC,IAAI,CAA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B,GAAG,CAAC,OAAkB,EAAE,EAAE;IACxD,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAA;IAC/C,OAAO,aAAa,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;AAC1C,CAAC,CAAA;AAHY,QAAA,mBAAmB,uBAG/B;AAEM,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAE,EAAE;IAClD,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAA;IACrB,OAAO,UAAU,KAAK,EAAE,CAAA;AAC1B,CAAC,CAAA;AAHY,QAAA,iBAAiB,qBAG7B"}
package/index.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { QueryParams } from './src/default/types'
2
+
3
+ export declare function findFirst<T>({
4
+ tableName,
5
+ dbClient,
6
+ select,
7
+ where,
8
+ groupBy,
9
+ orderBy,
10
+ }: QueryParams): Promise<T>
11
+
12
+ export declare function findMany<T>({
13
+ tableName,
14
+ dbClient,
15
+ select,
16
+ where,
17
+ groupBy,
18
+ orderBy,
19
+ limit,
20
+ }: QueryParams): Promise<T[]>
21
+
22
+ export declare function insert<T>({
23
+ tableName,
24
+ dbClient,
25
+ data,
26
+ returning,
27
+ }: QueryParams & { data: T; returning?: string[] }): Promise<T | void>
28
+
29
+ export declare function update<T>({
30
+ tableName,
31
+ dbClient,
32
+ id,
33
+ data,
34
+ returning,
35
+ }: QueryParams & { data: T; returning?: string[] }): Promise<T | void>
36
+
37
+ export declare function deleteOne({
38
+ tableName,
39
+ dbClient,
40
+ id,
41
+ permanently,
42
+ }: QueryParams & { permanently?: boolean }): Promise<void>
package/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ // Configs
2
+ export * from './src/db/initDb'
3
+
4
+ // Generic Repository
5
+ export * from './src/default/genericRepository'
package/jest.config.ts ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * For a detailed explanation regarding each configuration property, visit:
3
+ * https://jestjs.io/docs/configuration
4
+ */
5
+
6
+ import type { Config } from 'jest'
7
+
8
+ const config: Config = {
9
+ // All imported modules in your tests should be mocked automatically
10
+ // automock: false,
11
+
12
+ // Stop running tests after `n` failures
13
+ // bail: 0,
14
+
15
+ // The directory where Jest should store its cached dependency information
16
+ // cacheDirectory: "/private/var/folders/_3/bjt7nlhj13qd9dj4fnsdvwmc0000gn/T/jest_dx",
17
+
18
+ // Automatically clear mock calls, instances, contexts and results before every test
19
+ clearMocks: true,
20
+
21
+ // Indicates whether the coverage information should be collected while executing the test
22
+ collectCoverage: true,
23
+
24
+ // An array of glob patterns indicating a set of files for which coverage information should be collected
25
+ // collectCoverageFrom: undefined,
26
+
27
+ // The directory where Jest should output its coverage files
28
+ coverageDirectory: 'coverage',
29
+
30
+ // An array of regexp pattern strings used to skip coverage collection
31
+ // coveragePathIgnorePatterns: [
32
+ // "/node_modules/"
33
+ // ],
34
+
35
+ // Indicates which provider should be used to instrument code for coverage
36
+ coverageProvider: 'v8',
37
+
38
+ // A list of reporter names that Jest uses when writing coverage reports
39
+ // coverageReporters: [
40
+ // "json",
41
+ // "text",
42
+ // "lcov",
43
+ // "clover"
44
+ // ],
45
+
46
+ // An object that configures minimum threshold enforcement for coverage results
47
+ // coverageThreshold: undefined,
48
+
49
+ // A path to a custom dependency extractor
50
+ // dependencyExtractor: undefined,
51
+
52
+ // Make calling deprecated APIs throw helpful error messages
53
+ // errorOnDeprecated: false,
54
+
55
+ // The default configuration for fake timers
56
+ // fakeTimers: {
57
+ // "enableGlobally": false
58
+ // },
59
+
60
+ // Force coverage collection from ignored files using an array of glob patterns
61
+ // forceCoverageMatch: [],
62
+
63
+ // A path to a module which exports an async function that is triggered once before all test suites
64
+ // globalSetup: undefined,
65
+
66
+ // A path to a module which exports an async function that is triggered once after all test suites
67
+ // globalTeardown: undefined,
68
+
69
+ // A set of global variables that need to be available in all test environments
70
+ // globals: {},
71
+
72
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
73
+ // maxWorkers: "50%",
74
+
75
+ // An array of directory names to be searched recursively up from the requiring module's location
76
+ // moduleDirectories: [
77
+ // "node_modules"
78
+ // ],
79
+
80
+ // An array of file extensions your modules use
81
+ // moduleFileExtensions: [
82
+ // "js",
83
+ // "mjs",
84
+ // "cjs",
85
+ // "jsx",
86
+ // "ts",
87
+ // "tsx",
88
+ // "json",
89
+ // "node"
90
+ // ],
91
+
92
+ // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
93
+ // moduleNameMapper: {},
94
+
95
+ // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
96
+ // modulePathIgnorePatterns: [],
97
+
98
+ // Activates notifications for test results
99
+ // notify: false,
100
+
101
+ // An enum that specifies notification mode. Requires { notify: true }
102
+ // notifyMode: "failure-change",
103
+
104
+ // A preset that is used as a base for Jest's configuration
105
+ // preset: undefined,
106
+
107
+ // Run tests from one or more projects
108
+ // projects: undefined,
109
+
110
+ // Use this configuration option to add custom reporters to Jest
111
+ // reporters: undefined,
112
+
113
+ // Automatically reset mock state before every test
114
+ // resetMocks: false,
115
+
116
+ // Reset the module registry before running each individual test
117
+ // resetModules: false,
118
+
119
+ // A path to a custom resolver
120
+ // resolver: undefined,
121
+
122
+ // Automatically restore mock state and implementation before every test
123
+ // restoreMocks: false,
124
+
125
+ // The root directory that Jest should scan for tests and modules within
126
+ // rootDir: undefined,
127
+
128
+ // A list of paths to directories that Jest should use to search for files in
129
+ // roots: [
130
+ // "<rootDir>"
131
+ // ],
132
+
133
+ // Allows you to use a custom runner instead of Jest's default test runner
134
+ // runner: "jest-runner",
135
+
136
+ // The paths to modules that run some code to configure or set up the testing environment before each test
137
+ // setupFiles: [],
138
+
139
+ // A list of paths to modules that run some code to configure or set up the testing framework before each test
140
+ // setupFilesAfterEnv: [],
141
+
142
+ // The number of seconds after which a test is considered as slow and reported as such in the results.
143
+ // slowTestThreshold: 5,
144
+
145
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
146
+ // snapshotSerializers: [],
147
+
148
+ // The test environment that will be used for testing
149
+ // testEnvironment: "jest-environment-node",
150
+
151
+ // Options that will be passed to the testEnvironment
152
+ // testEnvironmentOptions: {},
153
+
154
+ // Adds a location field to test results
155
+ // testLocationInResults: false,
156
+
157
+ // The glob patterns Jest uses to detect test files
158
+ // testMatch: [
159
+ // "**/__tests__/**/*.[jt]s?(x)",
160
+ // "**/?(*.)+(spec|test).[tj]s?(x)"
161
+ // ],
162
+
163
+ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
164
+ // testPathIgnorePatterns: [
165
+ // "/node_modules/"
166
+ // ],
167
+
168
+ // The regexp pattern or array of patterns that Jest uses to detect test files
169
+ // testRegex: [],
170
+
171
+ // This option allows the use of a custom results processor
172
+ // testResultsProcessor: undefined,
173
+
174
+ // This option allows use of a custom test runner
175
+ // testRunner: "jest-circus/runner",
176
+
177
+ // A map from regular expressions to paths to transformers
178
+ // transform: undefined,
179
+
180
+ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
181
+ // transformIgnorePatterns: [
182
+ // "/node_modules/",
183
+ // "\\.pnp\\.[^\\/]+$"
184
+ // ],
185
+
186
+ // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
187
+ // unmockedModulePathPatterns: undefined,
188
+
189
+ // Indicates whether each individual test should be reported during the run
190
+ // verbose: undefined,
191
+
192
+ // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
193
+ // watchPathIgnorePatterns: [],
194
+
195
+ // Whether to use watchman for file crawling
196
+ // watchman: true,
197
+ }
198
+
199
+ export default config
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@starbemtech/star-db-query-builder",
3
+ "version": "1.0.0",
4
+ "description": "A query builder to be used with mysql or postgres",
5
+ "author": "Julio Sousa <julio.sousa@starbem.app>",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "license": "MIT",
9
+ "engines": {
10
+ "node": ">=16.13",
11
+ "pnpm": ">=8.6.7 <9"
12
+ },
13
+ "scripts": {
14
+ "build": "tsc",
15
+ "prepare": "husky",
16
+ "test": "jest",
17
+ "coverage": "jest --watchAll --coverage"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/starbem/star-db-query-builder.git"
22
+ },
23
+ "bugs": {
24
+ "url": "https://github.com/starbem/star-db-query-builder/issues"
25
+ },
26
+ "keywords": [
27
+ "javascript",
28
+ "postgres",
29
+ "mysql",
30
+ "sql",
31
+ "database"
32
+ ],
33
+ "devDependencies": {
34
+ "@types/jest": "^29.5.12",
35
+ "@types/mysql": "^2.15.26",
36
+ "@types/node": "^20.11.30",
37
+ "@types/pg": "^8.11.4",
38
+ "@typescript-eslint/eslint-plugin": "^7.4.0",
39
+ "@typescript-eslint/parser": "^7.4.0",
40
+ "eslint": "^8.57.0",
41
+ "eslint-config-prettier": "^9.1.0",
42
+ "eslint-plugin-jest": "^27.9.0",
43
+ "eslint-plugin-prettier": "^5.1.3",
44
+ "git-commit-msg-linter": "^5.0.7",
45
+ "husky": "^9.0.11",
46
+ "jest": "^29.7.0",
47
+ "lint-staged": "^15.2.2",
48
+ "prettier": "^3.2.5",
49
+ "typescript": "^5.4.3"
50
+ },
51
+ "dependencies": {
52
+ "mysql2": "^3.9.3",
53
+ "pg": "^8.11.3"
54
+ },
55
+ "lint-staged": {
56
+ "*.{ts}": [
57
+ "eslint --fix",
58
+ "prettier --write"
59
+ ]
60
+ },
61
+ "husky": {
62
+ "hooks": {
63
+ "pre-commit": "lint-staged"
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,6 @@
1
+ import { DBClients } from '../default/types'
2
+
3
+ export type IDatabaseClient = {
4
+ clientType: DBClients
5
+ query: <T>(sql: string, params?: any[]) => Promise<T>
6
+ }
@@ -0,0 +1,27 @@
1
+ import { Pool as PgPool } from 'pg'
2
+ import { createPool as createMySqlPool } from 'mysql2/promise'
3
+ import { createPgClient } from './pgClient'
4
+ import { createMysqlClient } from './mysqlClient'
5
+ import { IDatabaseClient } from './IDatabaseClient'
6
+
7
+ let dbClient: IDatabaseClient | null = null
8
+
9
+ export const initDb = (config: { type: 'pg' | 'mysql'; options: any }) => {
10
+ if (config.type === 'pg') {
11
+ const pool = new PgPool(config.options)
12
+ dbClient = createPgClient(pool)
13
+ } else if (config.type === 'mysql') {
14
+ const pool = createMySqlPool(config.options)
15
+ dbClient = createMysqlClient(pool)
16
+ } else {
17
+ throw new Error('Unsupported database type')
18
+ }
19
+ }
20
+
21
+ export const getDbClient = (): IDatabaseClient => {
22
+ if (!dbClient) {
23
+ throw new Error('Database client is not initialized')
24
+ }
25
+
26
+ return dbClient
27
+ }
@@ -0,0 +1,10 @@
1
+ import { Pool } from 'mysql2/promise'
2
+ import { IDatabaseClient } from './IDatabaseClient'
3
+
4
+ export const createMysqlClient = (pool: Pool): IDatabaseClient => ({
5
+ clientType: 'mysql',
6
+ query: async <T>(sql: string, params?: any[]): Promise<T> => {
7
+ const [rows] = await pool.execute(sql, params)
8
+ return rows as unknown as T
9
+ },
10
+ })
@@ -0,0 +1,10 @@
1
+ import { Pool } from 'pg'
2
+ import { IDatabaseClient } from './IDatabaseClient'
3
+
4
+ export const createPgClient = (pool: Pool): IDatabaseClient => ({
5
+ clientType: 'pg',
6
+ query: async <T>(sql: string, params?: any[]): Promise<T> => {
7
+ const { rows } = await pool.query(sql, params)
8
+ return rows as unknown as T
9
+ },
10
+ })
@@ -0,0 +1,143 @@
1
+ import { QueryParams } from './types'
2
+ import {
3
+ createGroupByClause,
4
+ createLimitClause,
5
+ createOrderByClause,
6
+ generatePlaceholders,
7
+ createSelectFields,
8
+ createWhereClause,
9
+ generateSetClause,
10
+ } from './utils'
11
+
12
+ export const findFirst = async <T>({
13
+ tableName,
14
+ dbClient,
15
+ select,
16
+ where,
17
+ groupBy,
18
+ orderBy,
19
+ }: QueryParams): Promise<T> => {
20
+ if (!tableName) throw new Error('Table name is required')
21
+ if (!dbClient) throw new Error('DB client is required')
22
+
23
+ const fields = createSelectFields(select)
24
+ const [whereClause, params] = createWhereClause(where)
25
+ const orderByClause = createOrderByClause(orderBy)
26
+ const groupByClause = createGroupByClause(groupBy)
27
+
28
+ const rows = await dbClient.query<T>(
29
+ `SELECT ${fields} FROM ${tableName}
30
+ ${whereClause.length > 7 ? whereClause : ''}
31
+ ${groupByClause}
32
+ ${orderByClause}
33
+ `,
34
+ [params]
35
+ )
36
+
37
+ return rows[0] || null
38
+ }
39
+
40
+ export const findMany = async <T>({
41
+ tableName,
42
+ dbClient,
43
+ select,
44
+ where,
45
+ groupBy,
46
+ orderBy,
47
+ limit,
48
+ }: QueryParams): Promise<T[]> => {
49
+ if (!tableName) throw new Error('Table name is required')
50
+ if (!dbClient) throw new Error('DB client is required')
51
+
52
+ const fields = createSelectFields(select)
53
+ const [whereClause, params] = createWhereClause(where)
54
+ const orderByClause = createOrderByClause(orderBy)
55
+ const groupByClause = createGroupByClause(groupBy)
56
+ const limitClause = createLimitClause(limit)
57
+
58
+ const rows = await dbClient.query<T[]>(
59
+ `SELECT ${fields} FROM ${tableName}
60
+ ${whereClause.length > 7 ? whereClause : ''}
61
+ ${groupByClause}
62
+ ${orderByClause}
63
+ ${limitClause}
64
+ `,
65
+ [params]
66
+ )
67
+
68
+ return rows || []
69
+ }
70
+
71
+ export const insert = async <T>({
72
+ tableName,
73
+ dbClient,
74
+ data,
75
+ returning,
76
+ }: QueryParams & { data: T; returning?: string[] }): Promise<T | void> => {
77
+ if (!tableName) throw new Error('Table name is required')
78
+ if (!dbClient) throw new Error('DB client is required')
79
+ if (!data) throw new Error('Data object is required')
80
+
81
+ const keys = Object.keys(data)
82
+ const values = Object.values(data)
83
+
84
+ const placeholders = generatePlaceholders(keys, dbClient.clientType)
85
+ let query = `INSERT INTO ${tableName} (${keys.join(', ')}) VALUES (${placeholders})`
86
+
87
+ if (dbClient.clientType === 'pg') {
88
+ if (returning && returning.length > 0) {
89
+ query += ` RETURNING ${createSelectFields(returning)}`
90
+ }
91
+ }
92
+
93
+ const inserted = await dbClient.query<T[]>(query, values)
94
+
95
+ if (dbClient.clientType === 'pg') return inserted[0]
96
+ }
97
+
98
+ export const update = async <T>({
99
+ tableName,
100
+ dbClient,
101
+ id,
102
+ data,
103
+ returning,
104
+ }: QueryParams & { data: T; returning?: string[] }): Promise<T | void> => {
105
+ if (!tableName) throw new Error('Table name is required')
106
+ if (!dbClient) throw new Error('DB client is required')
107
+ if (!id) throw new Error('ID is required')
108
+ if (!data) throw new Error('Data object is required')
109
+
110
+ const keys = Object.keys(data)
111
+ const values: any[] = Object.values(data)
112
+
113
+ const setClause = generateSetClause(keys, dbClient.clientType)
114
+ let query = `UPDATE ${tableName} SET ${setClause} WHERE ${id}`
115
+
116
+ if (dbClient.clientType === 'pg') {
117
+ if (returning && returning.length > 0) {
118
+ query += ` RETURNIN ${createSelectFields(returning)}`
119
+ }
120
+ }
121
+
122
+ const updated = await dbClient.query<T[]>(query, values)
123
+
124
+ if (dbClient.clientType === 'pg') return updated[0]
125
+ }
126
+
127
+ export const deleteOne = async ({
128
+ tableName,
129
+ dbClient,
130
+ id,
131
+ permanently = false,
132
+ }: QueryParams & { permanently?: boolean }): Promise<void> => {
133
+ if (!tableName) throw new Error('Table name is required')
134
+ if (!dbClient) throw new Error('DB client is required')
135
+ if (!id) throw new Error('ID is required')
136
+
137
+ await dbClient.query(
138
+ permanently
139
+ ? `DELETE FROM ${tableName} WHERE id = ${dbClient.clientType === 'pg' ? '$1' : '?'}`
140
+ : `UPDATE ${tableName} SET status = 'deleted' WHERE id = ${dbClient.clientType === 'pg' ? '$1' : '?'}`,
141
+ [id]
142
+ )
143
+ }
@@ -0,0 +1,53 @@
1
+ import { IDatabaseClient } from '../db/IDatabaseClient'
2
+
3
+ export interface QueryExec {
4
+ text: string
5
+ values?: any[]
6
+ }
7
+
8
+ type SimpleValue = string | number | boolean | Date
9
+
10
+ type ConditionOperator = 'AND' | 'OR'
11
+
12
+ interface OperatorCondition {
13
+ operator:
14
+ | 'LIKE'
15
+ | '='
16
+ | '>'
17
+ | '<'
18
+ | 'IN'
19
+ | 'BETWEEN'
20
+ | '!='
21
+ | '<='
22
+ | '>='
23
+ | 'NOT IN'
24
+ | 'LIKE'
25
+ | 'NOT LIKE'
26
+ value: SimpleValue | SimpleValue[]
27
+ }
28
+
29
+ export type DBClients = 'pg' | 'mysql'
30
+
31
+ export interface CompositeCondition {
32
+ type: ConditionOperator
33
+ conditions: Condition[]
34
+ }
35
+
36
+ export type Condition = SimpleValue | OperatorCondition | CompositeCondition
37
+
38
+ export interface Conditions {
39
+ [key: string]: Condition
40
+ }
41
+
42
+ export type OrderBy = { field: string; direction: 'ASC' | 'DESC' }[]
43
+
44
+ export interface QueryParams {
45
+ tableName: string
46
+ dbClient: IDatabaseClient
47
+ id?: string
48
+ select?: string[]
49
+ where?: Conditions
50
+ orderBy?: OrderBy
51
+ groupBy?: string[]
52
+ limit?: number
53
+ }
@@ -0,0 +1,107 @@
1
+ import {
2
+ Conditions,
3
+ Condition,
4
+ CompositeCondition,
5
+ OrderBy,
6
+ DBClients,
7
+ } from './types'
8
+
9
+ const arrayToStringWithQuotes = (items: string[]): string => {
10
+ const itemsWithQuotes = items.map((item) => `"${item}"`)
11
+ return itemsWithQuotes.join(', ')
12
+ }
13
+
14
+ export const createSelectFields = (fields?: string[]): string => {
15
+ return fields && fields.length > 0 ? arrayToStringWithQuotes(fields) : '*'
16
+ }
17
+
18
+ export const generatePlaceholders = (
19
+ keys: any[],
20
+ clientType: DBClients
21
+ ): string => {
22
+ return keys
23
+ .map((_, index) => (clientType === 'pg' ? `$${index + 1}` : '?'))
24
+ .join(', ')
25
+ }
26
+
27
+ export const generateSetClause = (
28
+ keys: any[],
29
+ clientType: DBClients
30
+ ): string => {
31
+ return keys
32
+ .map((key, index) =>
33
+ clientType === 'pg' ? `${key} = $${index + 1}` : `${key} = ?`
34
+ )
35
+ .join(', ')
36
+ }
37
+
38
+ export const createWhereClause = (
39
+ conditions: Conditions = {},
40
+ startIndex: number = 1
41
+ ): [string, any[], number] => {
42
+ let index = startIndex
43
+ const whereParts: string[] = []
44
+ const values: any[] = []
45
+
46
+ const processCondition = (key: string, condition: Condition): number => {
47
+ if (typeof condition === 'object' && condition !== null) {
48
+ if ('operator' in condition && 'value' in condition) {
49
+ const { operator, value } = condition
50
+ if (Array.isArray(value)) {
51
+ const placeholders = value.map(() => `$${index++}`).join(', ')
52
+ if (operator === 'BETWEEN') {
53
+ whereParts.push(
54
+ `"${key}" ${operator} ${placeholders.replace(', ', ' AND ')}`
55
+ )
56
+ } else {
57
+ whereParts.push(`"${key}" ${operator} (${placeholders})`)
58
+ }
59
+ values.push(...value)
60
+ } else {
61
+ whereParts.push(`"${key}" ${operator} $${index++}`)
62
+ values.push(value)
63
+ }
64
+ } else if ('type' in condition && 'conditions' in condition) {
65
+ const compositeCondition: CompositeCondition = condition
66
+ const subWhereParts: string[] = []
67
+ compositeCondition.conditions.forEach((subCondition) => {
68
+ // Recurso: criar uma chave fictícia, pois as condições compostas não necessitam de chave
69
+ index = processCondition('', subCondition)
70
+ })
71
+ whereParts.push(
72
+ `(${subWhereParts.join(` ${compositeCondition.type} `)})`
73
+ )
74
+ }
75
+ } else if (key) {
76
+ // Condição simples
77
+ whereParts.push(`"${key}" = $${index}`)
78
+ values.push(condition)
79
+ index++
80
+ }
81
+ return index
82
+ }
83
+
84
+ Object.entries(conditions).forEach(([key, value]) => {
85
+ index = processCondition(key, value)
86
+ })
87
+
88
+ const whereClause =
89
+ whereParts.length > 0 ? ` WHERE ${whereParts.join(' AND ')}` : ''
90
+ return [whereClause, values, index]
91
+ }
92
+
93
+ export const createOrderByClause = (orderBy?: OrderBy) => {
94
+ if (!orderBy || orderBy.length === 0) return ''
95
+ const clause = orderBy.map((o) => `${o.field} ${o.direction}`).join(', ')
96
+ return ` ORDER BY ${clause}`
97
+ }
98
+
99
+ export const createGroupByClause = (groupBy?: string[]) => {
100
+ if (!groupBy || groupBy.length === 0) return ''
101
+ return ` GROUP BY ${groupBy.join(', ')}`
102
+ }
103
+
104
+ export const createLimitClause = (limit?: number) => {
105
+ if (!limit) return ''
106
+ return ` LIMIT ${limit}`
107
+ }