@qrvey/data-persistence 0.3.6-beta.1 → 0.3.6-bundle

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.
@@ -1,728 +0,0 @@
1
- import { findIdColumnName, buildAggFunctionAlias, PersistenceErrorWrapper, getTableName } from './chunk-DHIGNHXS.mjs';
2
- import { __spreadValues, __spreadProps, DEFAULT_PG_SCHEMA, POSTGRES_FILTER_OPERATOR_MAP, DYNAMO_DB_UPDATE_ACTIONS } from './chunk-6MOAJFFY.mjs';
3
- import format from 'pg-format';
4
- import { Client } from 'pg';
5
-
6
- var ConnectionService = class {
7
- get connectionString() {
8
- const connectionString = process.env.MULTIPLATFORM_PG_CONNECTION_STRING || "";
9
- if (!connectionString) {
10
- throw new Error(
11
- "MULTIPLATFORM_PG_CONNECTION_STRING environment variable must be configured"
12
- );
13
- }
14
- return connectionString;
15
- }
16
- async getClient() {
17
- const client = new Client({
18
- connectionString: this.connectionString
19
- });
20
- await client.connect();
21
- return client;
22
- }
23
- releaseClient(client) {
24
- try {
25
- client.end();
26
- } catch (e) {
27
- console.log("Error releasing client");
28
- }
29
- }
30
- };
31
-
32
- // src/services/cruds/postgresql/query.service.ts
33
- var QueryService = class {
34
- constructor(poolClient) {
35
- this.poolClient = poolClient;
36
- this.connectionService = new ConnectionService();
37
- }
38
- async runQuery(queryText, values) {
39
- const client = await (this.poolClient ? this.poolClient : this.connectionService.getClient());
40
- try {
41
- const result = await client.query(queryText, values);
42
- return result;
43
- } catch (error) {
44
- console.log("[Postgresql-Client] Query Execution Failed:", error);
45
- throw error;
46
- } finally {
47
- if (!this.poolClient)
48
- this.connectionService.releaseClient(client);
49
- }
50
- }
51
- };
52
-
53
- // src/services/cruds/postgresql/postgreSqlClient.service.ts
54
- var PostgresqlClientService = class extends QueryService {
55
- constructor(tableSchema, poolClient) {
56
- super(poolClient);
57
- this.isCompositeFilter = function(value) {
58
- return "OR" in value || "AND" in value;
59
- };
60
- this.crudSchema = tableSchema;
61
- }
62
- get dbSchema() {
63
- return this.crudSchema.schema || DEFAULT_PG_SCHEMA;
64
- }
65
- get tableName() {
66
- return getTableName(this.crudSchema.table, "alias") || getTableName(this.crudSchema.table);
67
- }
68
- getWildcardValue(operator, value) {
69
- if (operator === "CONTAINS" /* CONTAINS */ || operator === "NOT_CONTAINS" /* NOT_CONTAINS */) {
70
- return "%" + value + "%";
71
- } else if (operator === "STARTS_WITH" /* STARTS_WITH */) {
72
- return value + "%";
73
- } else {
74
- return value;
75
- }
76
- }
77
- buildClause(operator, attribute, value) {
78
- var _a;
79
- const formattedValue = format.literal(value);
80
- operator = operator ? operator.toUpperCase() : "EQUAL" /* EQUAL */;
81
- const postgresOperator = POSTGRES_FILTER_OPERATOR_MAP[operator];
82
- if (!postgresOperator)
83
- throw new Error(`Unsupported filter operator: ${operator}`);
84
- const filterProperty = format.ident(attribute);
85
- const columnExists = !!this.crudSchema.columns[attribute];
86
- const columnType = columnExists && ((_a = this.crudSchema.columns[attribute]) == null ? void 0 : _a.type);
87
- const property = columnExists ? filterProperty : `("qvAttributes" ->> '${attribute}')`;
88
- if (operator === "IN" /* IN */) {
89
- const formattedValues = Array.isArray(value) ? value.map(format.literal) : [formattedValue];
90
- return `${property} ${postgresOperator} (${formattedValues.join(
91
- ", "
92
- )})`;
93
- }
94
- if (operator === "BETWEEN" /* BETWEEN */) {
95
- return `${property} ${postgresOperator} ${value[0]} AND ${value[1]}`;
96
- }
97
- if (operator === "NOT_EQUAL" /* NOT_EQUAL */ && value !== null) {
98
- return `(${property} ${postgresOperator} ${format.literal(
99
- value
100
- )} OR ${property} IS NULL)`;
101
- }
102
- if (operator === "NOT_EXIST" /* NOT_EXIST */ || operator === "EXIST" /* EXIST */) {
103
- return `${property} ${postgresOperator}`;
104
- }
105
- if ((operator === "CONTAINS" /* CONTAINS */ || operator === "NOT_CONTAINS" /* NOT_CONTAINS */) && columnType === "array") {
106
- const filterValue = typeof value === "number" ? value : `'${value}'`;
107
- let filterString = `${filterValue} = ANY(${property})`;
108
- if (operator === "NOT_CONTAINS" /* NOT_CONTAINS */) {
109
- if (value === null) {
110
- filterString = `(NOT (${filterString}))`;
111
- } else {
112
- filterString = `(NOT (${filterString}) or ${property} IS NULL)`;
113
- }
114
- }
115
- return filterString;
116
- }
117
- const wildcardValue = this.getWildcardValue(operator, value);
118
- return `${property} ${postgresOperator} ${format.literal(
119
- wildcardValue
120
- )}`;
121
- }
122
- buildFilterClause(filters, logicOperator) {
123
- if (Array.isArray(filters)) {
124
- const filterClauses = filters.map((filter) => {
125
- return this.buildClause(
126
- filter.operator,
127
- filter.attribute,
128
- filter.value
129
- );
130
- });
131
- return filterClauses.join(
132
- ` ${logicOperator != null ? logicOperator : "AND" /* AND */} `
133
- );
134
- } else {
135
- return this.buildQueryByClause(filters);
136
- }
137
- }
138
- buildQueryByClause(filters) {
139
- let filterClauses = "";
140
- let isFirstFilter = true;
141
- for (const [key, value] of Object.entries(filters)) {
142
- if (!isFirstFilter) {
143
- filterClauses += key === "AND" ? " AND " : " OR ";
144
- }
145
- if (this.isCompositeFilter(value)) {
146
- filterClauses += "(";
147
- filterClauses += this.buildQueryByClause(
148
- value
149
- );
150
- filterClauses += ")";
151
- } else {
152
- value.forEach((filter) => {
153
- let clause = "";
154
- if (this.isCompositeFilter(filter)) {
155
- clause = `(${this.buildQueryByClause(
156
- filter
157
- )})`;
158
- } else {
159
- clause = this.buildClause(
160
- filter.operator,
161
- filter.attribute,
162
- filter.value
163
- );
164
- }
165
- filterClauses += `${clause} ${key} `;
166
- });
167
- }
168
- isFirstFilter = false;
169
- }
170
- filterClauses = filterClauses.replace(/\s+(AND|OR)\s*$/, "");
171
- return filterClauses;
172
- }
173
- formatOrderByItem(sort) {
174
- return `${format.ident(sort.column)} ${sort.direction || "ASC" /* ASC */}`;
175
- }
176
- buildOrderByClause(querySorting) {
177
- try {
178
- return querySorting.map(this.formatOrderByItem).join(", ");
179
- } catch (error) {
180
- return "";
181
- }
182
- }
183
- formatArray(array) {
184
- const isNumberArray = typeof array[0] === "number";
185
- if (isNumberArray) {
186
- return `{${array.join(",")}}`;
187
- } else {
188
- return `{${array.map((val) => `"${val}"`).join(",")}}`;
189
- }
190
- }
191
- formatValue(value) {
192
- if (Array.isArray(value)) {
193
- if (!(value == null ? void 0 : value.length))
194
- return "{}";
195
- const isNumberArray = typeof value[0] === "number";
196
- if (isNumberArray) {
197
- return `{${value.join(",")}}`;
198
- } else {
199
- return `{${value.map((val) => `"${val}"`).join(",")}}`;
200
- }
201
- }
202
- return value;
203
- }
204
- async createCommand(data) {
205
- const keys = Object.keys(data[0]);
206
- const values = data.map(
207
- (item) => keys.map((key) => this.formatValue(item[key]))
208
- );
209
- const query = format(
210
- `INSERT INTO ${format.ident(this.dbSchema)}.${format.ident(
211
- this.tableName
212
- )} (%I) VALUES %L RETURNING *;`,
213
- keys,
214
- values
215
- );
216
- return this.runQuery(query);
217
- }
218
- addFiltersToQuery(query, filters) {
219
- if (!filters)
220
- return query;
221
- const isValidArrayFilters = Array.isArray(filters) && (filters == null ? void 0 : filters.length);
222
- const isValidCompositeFilters = this.isCompositeFilter(filters);
223
- if (isValidArrayFilters || isValidCompositeFilters)
224
- query += ` WHERE ${this.buildFilterClause(filters)}`;
225
- return query;
226
- }
227
- addOrderByToQuery(query, orderBy) {
228
- if (orderBy)
229
- query += ` ORDER BY ${this.buildOrderByClause(orderBy)}`;
230
- return query;
231
- }
232
- addPaginationToQuery(query, pagination) {
233
- if (pagination) {
234
- const { limit, from } = pagination;
235
- if (limit)
236
- query += ` LIMIT ${limit}`;
237
- if (from)
238
- query += ` OFFSET ${from}`;
239
- }
240
- return query;
241
- }
242
- getSelectClause(aggregateFunction, fields = []) {
243
- if (aggregateFunction)
244
- return `CAST(${aggregateFunction}(1) AS INTEGER) AS "${buildAggFunctionAlias(
245
- aggregateFunction
246
- )}"`;
247
- if (!(fields == null ? void 0 : fields.length))
248
- return "*";
249
- return this.parseFields(fields).join(", ");
250
- }
251
- parseFields(fields) {
252
- const columnsFromSchema = Object.keys(
253
- this.crudSchema.columns
254
- );
255
- const attributes = fields.filter((field) => columnsFromSchema.indexOf(field) !== -1).map((field) => `"${field}"`);
256
- fields.filter((field) => columnsFromSchema.indexOf(field) === -1).forEach((field) => {
257
- attributes.push(`"qvAttributes" ->> '${field}' as "${field}"`);
258
- });
259
- return attributes;
260
- }
261
- async findCommand(options = {}) {
262
- let query = `SELECT ${this.getSelectClause(
263
- options.aggregateFunction,
264
- options.fields
265
- )} FROM ${format.ident(this.dbSchema)}.${format.ident(this.tableName)}`;
266
- query = this.addFiltersToQuery(query, options.filters);
267
- if (!options.aggregateFunction) {
268
- query = this.addOrderByToQuery(query, options.sorting);
269
- query = this.addPaginationToQuery(query, options.pagination);
270
- }
271
- return (await this.runQuery(query)).rows;
272
- }
273
- sanitizeValue(value) {
274
- if (Array.isArray(value)) {
275
- if (value.length === 0)
276
- ;
277
- const formattedArray = value.map((item) => {
278
- if (typeof item === "string") {
279
- return `'${item}'`;
280
- } else if (typeof item === "object") {
281
- return JSON.stringify(item);
282
- } else {
283
- return item;
284
- }
285
- }).join(",");
286
- return JSON.stringify(formattedArray);
287
- } else {
288
- return format.literal(value);
289
- }
290
- }
291
- async updateCommand(filters, data) {
292
- let query = `UPDATE ${format.ident(this.dbSchema)}.${format.ident(
293
- this.tableName
294
- )} SET`;
295
- const updateClauses = Object.entries(data).map(([key, value]) => {
296
- const dbValue = format.literal(this.formatValue(value));
297
- return `${format.ident(key)} = ${dbValue}`;
298
- });
299
- query += ` ${updateClauses.join(", ")}`;
300
- query += " WHERE ";
301
- query += this.buildFilterClause(filters);
302
- return this.runQuery(query);
303
- }
304
- buildFilterClauseForFilterGroups(filterGroups) {
305
- const filterClauses = filterGroups.map((filterGroup) => {
306
- return `(${this.buildFilterClause(filterGroup)})`;
307
- });
308
- return filterClauses.join(" OR ");
309
- }
310
- async deleteCommand(filters, useFilterGroups = false) {
311
- let query = `DELETE FROM ${format.ident(this.dbSchema)}.${format.ident(
312
- this.tableName
313
- )}`;
314
- if (filters) {
315
- query += " WHERE ";
316
- if (useFilterGroups) {
317
- query += this.buildFilterClauseForFilterGroups(
318
- filters
319
- );
320
- } else {
321
- query += this.buildFilterClause(
322
- filters
323
- );
324
- }
325
- }
326
- return this.runQuery(query);
327
- }
328
- query(queryText, values) {
329
- return this.runQuery(queryText, values);
330
- }
331
- async updateExpressionCommand(filters, actions, options = {}) {
332
- let query = `UPDATE ${format.ident(this.dbSchema)}.${format.ident(
333
- this.tableName
334
- )} SET`;
335
- const set = actions.SET || [];
336
- const add = actions.ADD || [];
337
- const columns = this.crudSchema.columns;
338
- const setValues = this.replacePathAndValueByAttributeNames(
339
- set,
340
- options,
341
- columns,
342
- DYNAMO_DB_UPDATE_ACTIONS.SET
343
- );
344
- const addValues = this.replacePathAndValueByAttributeNames(
345
- add,
346
- options,
347
- columns,
348
- DYNAMO_DB_UPDATE_ACTIONS.ADD
349
- );
350
- const setValuesAndAddValues = setValues.concat(addValues);
351
- const updateClauses = [];
352
- const jsonSetExpressionGroup = {};
353
- const queryFunctions = [];
354
- setValuesAndAddValues.forEach((expression) => {
355
- const { path, value, createNewColumn, actionName, dynamoFuncName } = expression;
356
- if (dynamoFuncName) {
357
- queryFunctions.push({ path, value, dynamoFuncName });
358
- }
359
- if (path.includes(".") && !dynamoFuncName) {
360
- const jsonExpr = this.getJSONBSetExpressionByAction(
361
- path,
362
- value,
363
- {
364
- createNewColumn,
365
- actionName
366
- }
367
- );
368
- const columnName = jsonExpr.columnName;
369
- if (!jsonSetExpressionGroup[columnName]) {
370
- jsonSetExpressionGroup[columnName] = [jsonExpr];
371
- } else {
372
- jsonSetExpressionGroup[columnName].push(jsonExpr);
373
- }
374
- } else if (!dynamoFuncName) {
375
- let expValue;
376
- const column = this.crudSchema.columns[path];
377
- if ((column == null ? void 0 : column.type) == void 0)
378
- throw `Column type definition for column: (${path}) must be in the CrudSchema`;
379
- let formattedValue;
380
- switch (column.type) {
381
- case "object":
382
- {
383
- const valueSerialized = this.serializeJSONValue(value);
384
- expValue = `'${valueSerialized}'::jsonb`;
385
- }
386
- break;
387
- case "array":
388
- formattedValue = format.literal(value);
389
- expValue = `ARRAY[${formattedValue}]`;
390
- break;
391
- default:
392
- formattedValue = format.literal(value);
393
- expValue = formattedValue;
394
- break;
395
- }
396
- this.crudSchema.columns;
397
- updateClauses.push(`${format.ident(path)} = ${expValue}`);
398
- }
399
- });
400
- if (Object.keys(jsonSetExpressionGroup).length > 0) {
401
- Object.keys(jsonSetExpressionGroup).forEach((groupIndex) => {
402
- const jsonSetExpression = this.buildJSONBExpression(
403
- jsonSetExpressionGroup[groupIndex],
404
- "jsonb_set"
405
- );
406
- updateClauses.push(`${groupIndex} = ${jsonSetExpression}`);
407
- });
408
- }
409
- if (queryFunctions.length > 0) {
410
- queryFunctions.forEach((queryFunction) => {
411
- updateClauses.push(
412
- `${format.ident(queryFunction.path)} = ${queryFunction.value}`
413
- );
414
- });
415
- }
416
- query += ` ${updateClauses.join(", ")}`;
417
- query += " WHERE ";
418
- query += this.buildFilterClause(filters);
419
- return this.runQuery(query);
420
- }
421
- /**
422
- * @description Builds a jsonb expression like jsonb_insert, or jsonb_set
423
- * @param jsonSetExpressions
424
- * @param functionName
425
- * @returns
426
- */
427
- buildJSONBExpression(jsonSetExpressions, functionName) {
428
- let jsonSetStringExpr = "";
429
- jsonSetExpressions.forEach((expression, index) => {
430
- const { columnName, jsonExpr } = expression;
431
- if (index === 0) {
432
- jsonSetStringExpr = `${functionName}(${columnName},${jsonExpr})`;
433
- } else {
434
- jsonSetStringExpr = `${functionName}(${jsonSetStringExpr},${jsonExpr})`;
435
- }
436
- });
437
- return jsonSetStringExpr;
438
- }
439
- /**
440
- * @description Serializes a JSON value
441
- * @param value
442
- * @returns
443
- */
444
- serializeJSONValue(value) {
445
- const valueSerialized = typeof value == "object" ? `${JSON.stringify(value).replace(/'/g, "''")}` : value;
446
- return valueSerialized;
447
- }
448
- getJSONBSetExpressionByAction(path, value, options) {
449
- path = path.replace(/\[(\d+)\]/g, ".$1");
450
- const pathSplitted = path.split(".");
451
- const parentPath = pathSplitted[0];
452
- const { createNewColumn, actionName } = options;
453
- const pathSerialized = pathSplitted.slice(1).join(",");
454
- const valueSerialized = `'${JSON.stringify(value).replace(
455
- /'/g,
456
- "''"
457
- )}'`;
458
- if (actionName == DYNAMO_DB_UPDATE_ACTIONS.ADD) {
459
- if (typeof value != "string" && !isNaN(value)) {
460
- const resultExpr = {
461
- jsonExpr: `'{${pathSerialized}}',to_jsonb(COALESCE(("${parentPath}"#>'{${pathSerialized}}')::numeric,0) + ${valueSerialized})`,
462
- columnName: `"${parentPath}"`
463
- };
464
- return resultExpr;
465
- }
466
- }
467
- return {
468
- jsonExpr: `'{${pathSerialized}}',${valueSerialized},${createNewColumn}`,
469
- columnName: `"${parentPath}"`
470
- };
471
- }
472
- getListAppendDefFromValue(queryValue, columnType) {
473
- const regexListAppend = /list_append\(([^)]+)\)/gm;
474
- const listAppendString = "list_append(";
475
- const matchList = queryValue.match(regexListAppend) || [];
476
- const groupResult = matchList[0];
477
- if (groupResult) {
478
- const attributesFromGroup = groupResult.slice(listAppendString.length, -1).split(",");
479
- const attributes = {
480
- originalString: groupResult,
481
- path: attributesFromGroup[0].trim(),
482
- value: attributesFromGroup.slice(1).join(",").trim(),
483
- functionExpr: ""
484
- };
485
- if (columnType == "array") {
486
- attributes["functionExpr"] = this.buildArrayAppendExpr(attributes);
487
- } else {
488
- attributes["functionExpr"] = this.buildJsonbInsertExpr(attributes);
489
- }
490
- return attributes;
491
- }
492
- return null;
493
- }
494
- buildArrayAppendExpr(params) {
495
- const arrayPath = params.path.split(".");
496
- const columnName = arrayPath.shift();
497
- return `ARRAY_APPEND("${columnName}",${params.value})`;
498
- }
499
- buildJsonbInsertExpr(params) {
500
- const arrayPath = params.path.split(".");
501
- const columnName = arrayPath.shift();
502
- const jsonbInsertExpressions = this.getExpressionsByDefinitionForJSONBInsert(
503
- columnName,
504
- params.value
505
- );
506
- const expressions = this.buildJSONBExpression(
507
- jsonbInsertExpressions,
508
- "jsonb_insert"
509
- );
510
- return expressions;
511
- }
512
- getExpressionsByDefinitionForJSONBInsert(columnName, value) {
513
- const jsonbInsertExpressions = [];
514
- try {
515
- const parsedValue = JSON.parse(value);
516
- if (Array.isArray(parsedValue)) {
517
- parsedValue.forEach((arrayValue) => {
518
- jsonbInsertExpressions.push({
519
- jsonExpr: `'{0}','${this.serializeJSONValue(
520
- arrayValue
521
- )}'`,
522
- columnName: `"${columnName}"`
523
- });
524
- });
525
- } else {
526
- jsonbInsertExpressions.push({
527
- jsonExpr: `'{0}','${this.serializeJSONValue(parsedValue)}'`,
528
- columnName: `"${columnName}"`
529
- });
530
- }
531
- } catch (error) {
532
- jsonbInsertExpressions.push({
533
- jsonExpr: `'{0}','${value}'`,
534
- columnName: `"${columnName}"`
535
- });
536
- }
537
- return jsonbInsertExpressions;
538
- }
539
- getInsertExprFromJsonbDef(queryValue, columnType) {
540
- const listAppendParams = this.getListAppendDefFromValue(
541
- queryValue,
542
- columnType
543
- );
544
- if (listAppendParams != null) {
545
- queryValue = queryValue.replace(
546
- listAppendParams.originalString,
547
- listAppendParams.functionExpr
548
- );
549
- }
550
- return queryValue;
551
- }
552
- replacePathAndValueByAttributeNames(actions, options, columns, actionName) {
553
- return actions.map((action) => {
554
- action.path = this.replaceExpressionAttributeNames(
555
- action.path,
556
- options
557
- );
558
- if (typeof action.value == "string" && action.value.includes("list_append")) {
559
- action.path = action.path.split(".")[0];
560
- const column = columns[action.path];
561
- action.value = this.replaceExpressionAttributeValuesForDynamoFunctions(
562
- action.value,
563
- options
564
- );
565
- action.value = this.getInsertExprFromJsonbDef(
566
- action.value,
567
- column.type
568
- );
569
- action.dynamoFuncName = "list_append";
570
- } else {
571
- action.value = this.replaceExpressionAttributeValues(
572
- action.value,
573
- options
574
- );
575
- }
576
- action.actionName = actionName;
577
- action.createNewColumn = true;
578
- return action;
579
- });
580
- }
581
- replaceExpressionAttributeValuesForDynamoFunctions(value, options) {
582
- const { expressionAttributeNames, expressionAttributeValues } = options;
583
- const exprAttributeNamesKeys = expressionAttributeNames ? Object.keys(expressionAttributeNames) : [];
584
- const exprAttributeValuesKeys = expressionAttributeValues ? Object.keys(expressionAttributeValues) : [];
585
- if (exprAttributeNamesKeys.length > 0) {
586
- exprAttributeNamesKeys.forEach((exprAttribute) => {
587
- value = value.replace(
588
- exprAttribute,
589
- expressionAttributeNames[exprAttribute]
590
- );
591
- });
592
- }
593
- if (exprAttributeValuesKeys.length > 0) {
594
- exprAttributeValuesKeys.forEach((exprAttribute) => {
595
- const valueSerialized = this.serializeJSONValue(
596
- expressionAttributeValues[exprAttribute]
597
- );
598
- value = value.replace(exprAttribute, `${valueSerialized}`);
599
- });
600
- }
601
- return value;
602
- }
603
- replaceExpressionAttributeNames(path, options) {
604
- const { expressionAttributeNames } = options;
605
- if (expressionAttributeNames) {
606
- Object.keys(expressionAttributeNames).forEach(
607
- (attributeName) => {
608
- const attributeNameValue = expressionAttributeNames[attributeName];
609
- path = path.replace(attributeName, attributeNameValue);
610
- }
611
- );
612
- }
613
- return path;
614
- }
615
- replaceExpressionAttributeValues(value, options) {
616
- const { expressionAttributeValues } = options;
617
- if (expressionAttributeValues[value] != void 0) {
618
- return expressionAttributeValues[value];
619
- }
620
- return value;
621
- }
622
- };
623
-
624
- // src/services/cruds/postgresql/postgreSqlCrud.service.ts
625
- var PostgreSqlCrudService = class extends PostgresqlClientService {
626
- constructor(tableSchema) {
627
- super(tableSchema);
628
- this.tableSchema = tableSchema;
629
- }
630
- get idColumnName() {
631
- return findIdColumnName(this.tableSchema.columns);
632
- }
633
- normalizeInputData(inputData) {
634
- var _a;
635
- inputData.qvAttributes = {};
636
- for (const key in inputData) {
637
- if (!this.tableSchema.columns[key] && key !== "qvAttributes") {
638
- inputData.qvAttributes[key] = inputData[key];
639
- delete inputData[key];
640
- } else if (Array.isArray(inputData[key]) && ((_a = this.tableSchema.columns[key]) == null ? void 0 : _a.type) !== "array") {
641
- inputData[key] = JSON.stringify(inputData[key]);
642
- }
643
- }
644
- }
645
- getItem(data) {
646
- const resultItem = __spreadValues(__spreadValues({}, data), data.qvAttributes);
647
- delete resultItem["qvAttributes"];
648
- return resultItem;
649
- }
650
- prepareData(data) {
651
- const inputData = __spreadValues({}, data);
652
- this.normalizeInputData(inputData);
653
- return inputData;
654
- }
655
- create(data) {
656
- if (Array.isArray(data)) {
657
- const inputDataArray = data.map((item) => this.prepareData(item));
658
- return this.createCommand(inputDataArray).then((result) => ({
659
- unprocessedItems: result.filter((r) => !r.success).map((r) => r.inputData)
660
- }));
661
- } else {
662
- const inputData = this.prepareData(data);
663
- return this.createCommand([inputData]).then(
664
- (result) => result.rowCount ? this.getItem(result.rows[0]) : null
665
- );
666
- }
667
- }
668
- findItem(findOptions) {
669
- return this.findCommand(findOptions).then((data) => {
670
- return (data == null ? void 0 : data.length) ? this.getItem(data[0]) : null;
671
- });
672
- }
673
- async processQueryResult(findOptions, omitPagination = false) {
674
- const rows = await this.findCommand(findOptions);
675
- const items = rows.map(
676
- (row) => this.getItem(row)
677
- );
678
- const { limit, from } = (findOptions == null ? void 0 : findOptions.pagination) || {};
679
- const hasMoreRecords = items.length && items.length === limit;
680
- const newFrom = limit && hasMoreRecords ? limit + (from || 0) : null;
681
- const result = {
682
- items,
683
- pagination: omitPagination ? null : { limit, from: newFrom },
684
- count: items.length
685
- };
686
- return result;
687
- }
688
- async find(findOptions) {
689
- return this.processQueryResult(findOptions);
690
- }
691
- async findAll(findOptions) {
692
- return this.processQueryResult(findOptions, true);
693
- }
694
- async findCount(findOptions) {
695
- const items = await this.findCommand(__spreadProps(__spreadValues({}, findOptions), {
696
- aggregateFunction: "COUNT" /* COUNT */
697
- }));
698
- const aggFunctionProperty = buildAggFunctionAlias(
699
- "COUNT" /* COUNT */
700
- );
701
- const item = items.length ? items[0] : {};
702
- return item[aggFunctionProperty] || 0;
703
- }
704
- async update(filters, data) {
705
- const savedRecord = await this.findItem({ filters });
706
- const inputData = __spreadValues(__spreadValues({}, savedRecord), data);
707
- await this.updateCommand(filters, this.prepareData(inputData));
708
- return this.getItem(inputData);
709
- }
710
- async remove(filters, options) {
711
- await this.deleteCommand(filters, options == null ? void 0 : options.filterGroups);
712
- }
713
- runQuery(querySentence, values) {
714
- return super.runQuery(querySentence, values);
715
- }
716
- async updateExpressions(filters, actions, options) {
717
- const result = await this.updateExpressionCommand(
718
- filters,
719
- actions,
720
- options
721
- );
722
- return PersistenceErrorWrapper(result);
723
- }
724
- };
725
-
726
- export { PostgreSqlCrudService };
727
- //# sourceMappingURL=out.js.map
728
- //# sourceMappingURL=postgreSqlCrud.service-WTKLHYDV.mjs.map