@starbemtech/star-db-query-builder 1.0.2 → 1.0.3

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.
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,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,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,7 @@
1
+ import { IDatabaseClient } from './IDatabaseClient';
2
+ import { DBClients } from '../default/types';
3
+ export declare const initDb: <T>(config: {
4
+ type: DBClients;
5
+ options: T;
6
+ }) => void;
7
+ export declare const getDbClient: () => IDatabaseClient;
@@ -0,0 +1,36 @@
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)
11
+ throw new Error('Type is required. Accept values: pg | mysql');
12
+ if (!config.options)
13
+ throw new Error('Connection options is required');
14
+ if (config.type === 'pg') {
15
+ const pool = new pg_1.Pool(config.options);
16
+ dbClient = (0, pgClient_1.createPgClient)(pool);
17
+ console.log(`Postgres db client connect success`);
18
+ }
19
+ else if (config.type === 'mysql') {
20
+ const pool = (0, promise_1.createPool)(config.options);
21
+ dbClient = (0, mysqlClient_1.createMysqlClient)(pool);
22
+ console.info(`MySQL db client connect success.`);
23
+ }
24
+ else {
25
+ throw new Error('Unsupported database type');
26
+ }
27
+ };
28
+ exports.initDb = initDb;
29
+ const getDbClient = () => {
30
+ if (!dbClient) {
31
+ throw new Error('Database client is not initialized');
32
+ }
33
+ return dbClient;
34
+ };
35
+ exports.getDbClient = getDbClient;
36
+ //# 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;AAIjD,IAAI,QAAQ,GAA2B,IAAI,CAAA;AAEpC,MAAM,MAAM,GAAG,CAAI,MAAuC,EAAQ,EAAE;IACzE,IAAI,CAAC,MAAM,CAAC,IAAI;QACd,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAA;IAEhE,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;IAEtE,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;QAE/B,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAA;IACnD,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;QAElC,OAAO,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAA;IAClD,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAA;IAC9C,CAAC;AACH,CAAC,CAAA;AAnBY,QAAA,MAAM,UAmBlB;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,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I;QAAE,OAAO,OAAO,CAAC,CAAC,CAAC,CAAA;AACrD,CAAC,CAAA;AA3BY,QAAA,MAAM,UA2BlB;AAEM,MAAM,SAAS,GAAG,KAAK,EAAE,EAC9B,SAAS,EACT,QAAQ,EACR,EAAE,EACF,WAAW,GAAG,KAAK,GACqB,EAAiB,EAAE;IAC3D,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;IACzD,IAAI,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAA;IACvD,IAAI,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAA;IAE1C,MAAM,QAAQ,CAAC,KAAK,CAClB,WAAW;QACT,CAAC,CAAC,eAAe,SAAS,eAAe,QAAQ,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,EAAE;QACpF,CAAC,CAAC,UAAU,SAAS,sCAAsC,QAAQ,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,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,CAAC,IAAI,CAAC,CAAA;AACnC,CAAC,CAAA;AAEM,MAAM,kBAAkB,GAAG,CAAC,MAAiB,EAAU,EAAE;IAC9D,OAAO,MAAM,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;AAC5E,CAAC,CAAA;AAFY,QAAA,kBAAkB,sBAE9B;AAEM,MAAM,oBAAoB,GAAG,CAClC,IAAW,EACX,UAAqB,EACb,EAAE;IACV,OAAO,IAAI;SACR,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SAChE,IAAI,CAAC,IAAI,CAAC,CAAA;AACf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,CAAA;IAEF,MAAM,WAAW,GACf,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;IACnE,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;AACrC,CAAC,CAAA;AArDY,QAAA,iBAAiB,qBAqD7B;AAEM,MAAM,mBAAmB,GAAG,CAAC,OAAiB,EAAE,EAAE;IACvD,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAA;IAC/C,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACzE,OAAO,aAAa,MAAM,EAAE,CAAA;AAC9B,CAAC,CAAA;AAJY,QAAA,mBAAmB,uBAI/B;AAEM,MAAM,mBAAmB,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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starbemtech/star-db-query-builder",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "A query builder to be used with mysql or postgres",
5
5
  "author": "Julio Sousa <julio.sousa@starbem.app>",
6
6
  "main": "./dist/index.js",
@@ -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,41 @@
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
+ import { DBClients } from '../default/types'
7
+
8
+ let dbClient: IDatabaseClient | null = null
9
+
10
+ export const initDb = <T>(config: { type: DBClients; options: T }): void => {
11
+ if (!config.type)
12
+ throw new Error('Type is required. Accept values: pg | mysql')
13
+
14
+ if (!config.options) throw new Error('Connection options is required')
15
+
16
+ if (config.type === 'pg') {
17
+ const pool = new PgPool(config.options)
18
+ dbClient = createPgClient(pool)
19
+
20
+ console.log(
21
+ `@starbemtech/star-db-query-builder: Postgres db client created success`
22
+ )
23
+ } else if (config.type === 'mysql') {
24
+ const pool = createMySqlPool(config.options)
25
+ dbClient = createMysqlClient(pool)
26
+
27
+ console.info(
28
+ `@starbemtech/star-db-query-builder: MySQL db client created success.`
29
+ )
30
+ } else {
31
+ throw new Error('Unsupported database type')
32
+ }
33
+ }
34
+
35
+ export const getDbClient = (): IDatabaseClient => {
36
+ if (!dbClient) {
37
+ throw new Error('Database client is not initialized')
38
+ }
39
+
40
+ return dbClient
41
+ }
@@ -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
+ }