aws-service-stack 0.18.310 → 0.18.312
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/dist/repositories/base-db.repo.d.ts +0 -1
- package/dist/repositories/base-db.repo.interface.d.ts +0 -1
- package/dist/repositories/base-db.repo.interface.js.map +1 -1
- package/dist/repositories/base-db.repo.js +0 -17
- package/dist/repositories/base-db.repo.js.map +1 -1
- package/dist/service/base.service.d.ts +1 -1
- package/dist/service/base.service.interface.d.ts +1 -1
- package/dist/service/base.service.interface.js.map +1 -1
- package/dist/service/base.service.js +6 -0
- package/dist/service/base.service.js.map +1 -1
- package/dist/service/crud.service.js +2 -0
- package/dist/service/crud.service.js.map +1 -1
- package/package.json +1 -1
|
@@ -19,7 +19,6 @@ export declare class BaseRepoDBImpl<T extends BaseEntity> implements BaseRepoDB<
|
|
|
19
19
|
findById(id: string): Promise<T>;
|
|
20
20
|
findByIds(ids: string[]): Promise<T[]>;
|
|
21
21
|
find(filter: Filter): Promise<List<Partial<T>>>;
|
|
22
|
-
findAll(filter: Filter | string): Promise<Partial<T>[]>;
|
|
23
22
|
scan(filter: Filter): Promise<List<Partial<T>>>;
|
|
24
23
|
findOne(filter: Filter): Promise<T>;
|
|
25
24
|
findByIndex(indexName: string, value: string): Promise<List<Partial<T>>>;
|
|
@@ -132,7 +132,6 @@ export interface BaseRepoDB<T extends BaseEntity> extends CoreRepo<T> {
|
|
|
132
132
|
getTableName(): string;
|
|
133
133
|
/** Executes a DynamoDB Query strictly (requires indexName and indexValue). */
|
|
134
134
|
find(filter: Filter): Promise<List<Partial<T>>>;
|
|
135
|
-
findAll(filter: Filter): Promise<Partial<T>[]>;
|
|
136
135
|
/** Executes a DynamoDB Scan with optional non-index filters. */
|
|
137
136
|
scan(filter: Filter): Promise<List<Partial<T>>>;
|
|
138
137
|
incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-db.repo.interface.js","sourceRoot":"","sources":["../../src/repositories/base-db.repo.interface.ts"],"names":[],"mappings":"","sourcesContent":["import { DynamoIndexMap, List } from \"../index\";\nimport { CoreRepo } from \"./base-core.repo.interface\";\n\nimport { BaseEntity, Filter } from \"@chinggis/types\";\n\nexport interface BaseRepoDB<T extends BaseEntity> extends CoreRepo<T> {\n /**\n * Saves an entity by either creating it (if it does not exist) or updating it (if it does).\n *\n * @param entity - The entity to save.\n * @returns The saved entity.\n */\n save(entity: Partial<T>): Promise<T>;\n\n /**\n * Saves multiple entities by either creating or updating each one.\n *\n * @param entities - An array of entities to save.\n * @param isTransactional - Optional flag to indicate if the operation should be transactional.\n * @returns An array of saved entities.\n */\n saveMany(entities: Partial<T>[], isTransactional?: boolean): Promise<Partial<T>[]>;\n\n /**\n * Updates an existing entity.\n * Fails if the entity does not exist.\n *\n * @param entity - The entity with updated data.\n * @returns The updated entity.\n */\n update(entity: Partial<T>): Promise<T>;\n\n /**\n * Updates multiple existing entities.\n *\n * If `fieldNames` is **not provided**, the method performs a **batch update**\n * (e.g., using `BatchWriteItem` in DynamoDB, if supported). In this case, entire entities\n * are replaced or merged as a whole.\n *\n * If `fieldNames` **is provided**, each entity is updated individually, and only the\n * specified fields in `fieldNames` will be modified. This approach avoids overwriting\n * the entire entity and is useful for partial updates.\n *\n * Note:\n * - Entities must already exist in the data store.\n * - Batch update is not truly atomic; some partial updates may occur if errors happen mid-way.\n * - If partial field updates are needed, `fieldNames` must be used.\n *\n * @param entities - An array of entities with partial data to update.\n * @param isTransactional - Optional flag to indicate if the operation should be transactional.\n * @param fields - field names to update\n * @returns An array of successfully updated entities.\n */\n updateMany(entities: Partial<T>[], fields: string[], isTransactional?: boolean): Promise<boolean>;\n\n /**\n * Deletes an entity by its unique identifier.\n *\n * @param id - The ID of the entity to delete.\n * @returns True if the entity was successfully deleted; otherwise, false.\n */\n delete(id: string): Promise<boolean>;\n\n /**\n * Deletes multiple entities by their unique identifiers.\n *\n * @param ids - An array of entity IDs to delete.\n * @returns True if all entities were successfully deleted; otherwise, false.\n */\n deleteMany(ids: string[]): Promise<boolean>;\n\n /**\n * Executes a transactional write operation.\n * DynamoDB typically supports this for atomic operations.\n *\n * @param operations - An array of write operations (create, update, delete) to perform atomically.\n * @returns True if the transaction was successful; otherwise, false.\n */\n transactionWrite(operations: {\n create?: { tableName: string; item: Record<string, any> }[];\n update?: {\n tableName: string;\n key: { id: string };\n updateData: Record<string, any>;\n }[];\n delete?: { tableName: string; key: { id: string } }[];\n }): Promise<boolean>;\n\n /**\n * Executes a transactional read operation.\n * DynamoDB typically supports this for atomic read operations.\n *\n * @param operations - An array of read operations to perform atomically.\n * @returns An array of results from the transaction.\n */\n transactionRead<T>(operations: { id: string; sortKey?: string }[]): Promise<T[]>;\n\n /**\n * (Optional) Executes a transactional write operation.\n * DynamoDB typically only supports this.\n *\n * @param operations - An array of write operations to perform atomically.\n * @returns True if the transaction was successful; otherwise, false.\n */\n transactWrite?(operations: any[]): Promise<boolean>;\n\n /**\n * Deletes one or more fields (attributes) from a DynamoDB item by its partition key.\n *\n * This method uses the `REMOVE` operation of the UpdateExpression to remove specific fields\n * from an existing item in the table. It dynamically constructs the expression and returns\n * the updated item (after removal).\n *\n * @param id - The value of the partition key for the item to update.\n * @param fieldNames - An array of attribute names to be removed from the item.\n * @returns The updated item as a partial object, or `undefined` if no update was performed.\n */\n deleteFields(id: string, fieldNames: string[]): Promise<Partial<T>>;\n\n /**\n * (Optional) Executes a transactional read operation.\n * DynamoDB typically only supports this.\n *\n * @param operations - An array of read operations to perform atomically.\n * @returns An array of results from the transaction.\n */\n transactRead?<TResult = any>(operations: any[]): Promise<TResult[]>;\n\n setIndexMap(value: DynamoIndexMap): boolean;\n\n getIndexMap(): DynamoIndexMap;\n\n setTable(name: string): boolean;\n\n getTableName(): string;\n\n /** Executes a DynamoDB Query strictly (requires indexName and indexValue). */\n find(filter: Filter): Promise<List<Partial<T>>>;\n\n
|
|
1
|
+
{"version":3,"file":"base-db.repo.interface.js","sourceRoot":"","sources":["../../src/repositories/base-db.repo.interface.ts"],"names":[],"mappings":"","sourcesContent":["import { DynamoIndexMap, List } from \"../index\";\nimport { CoreRepo } from \"./base-core.repo.interface\";\n\nimport { BaseEntity, Filter } from \"@chinggis/types\";\n\nexport interface BaseRepoDB<T extends BaseEntity> extends CoreRepo<T> {\n /**\n * Saves an entity by either creating it (if it does not exist) or updating it (if it does).\n *\n * @param entity - The entity to save.\n * @returns The saved entity.\n */\n save(entity: Partial<T>): Promise<T>;\n\n /**\n * Saves multiple entities by either creating or updating each one.\n *\n * @param entities - An array of entities to save.\n * @param isTransactional - Optional flag to indicate if the operation should be transactional.\n * @returns An array of saved entities.\n */\n saveMany(entities: Partial<T>[], isTransactional?: boolean): Promise<Partial<T>[]>;\n\n /**\n * Updates an existing entity.\n * Fails if the entity does not exist.\n *\n * @param entity - The entity with updated data.\n * @returns The updated entity.\n */\n update(entity: Partial<T>): Promise<T>;\n\n /**\n * Updates multiple existing entities.\n *\n * If `fieldNames` is **not provided**, the method performs a **batch update**\n * (e.g., using `BatchWriteItem` in DynamoDB, if supported). In this case, entire entities\n * are replaced or merged as a whole.\n *\n * If `fieldNames` **is provided**, each entity is updated individually, and only the\n * specified fields in `fieldNames` will be modified. This approach avoids overwriting\n * the entire entity and is useful for partial updates.\n *\n * Note:\n * - Entities must already exist in the data store.\n * - Batch update is not truly atomic; some partial updates may occur if errors happen mid-way.\n * - If partial field updates are needed, `fieldNames` must be used.\n *\n * @param entities - An array of entities with partial data to update.\n * @param isTransactional - Optional flag to indicate if the operation should be transactional.\n * @param fields - field names to update\n * @returns An array of successfully updated entities.\n */\n updateMany(entities: Partial<T>[], fields: string[], isTransactional?: boolean): Promise<boolean>;\n\n /**\n * Deletes an entity by its unique identifier.\n *\n * @param id - The ID of the entity to delete.\n * @returns True if the entity was successfully deleted; otherwise, false.\n */\n delete(id: string): Promise<boolean>;\n\n /**\n * Deletes multiple entities by their unique identifiers.\n *\n * @param ids - An array of entity IDs to delete.\n * @returns True if all entities were successfully deleted; otherwise, false.\n */\n deleteMany(ids: string[]): Promise<boolean>;\n\n /**\n * Executes a transactional write operation.\n * DynamoDB typically supports this for atomic operations.\n *\n * @param operations - An array of write operations (create, update, delete) to perform atomically.\n * @returns True if the transaction was successful; otherwise, false.\n */\n transactionWrite(operations: {\n create?: { tableName: string; item: Record<string, any> }[];\n update?: {\n tableName: string;\n key: { id: string };\n updateData: Record<string, any>;\n }[];\n delete?: { tableName: string; key: { id: string } }[];\n }): Promise<boolean>;\n\n /**\n * Executes a transactional read operation.\n * DynamoDB typically supports this for atomic read operations.\n *\n * @param operations - An array of read operations to perform atomically.\n * @returns An array of results from the transaction.\n */\n transactionRead<T>(operations: { id: string; sortKey?: string }[]): Promise<T[]>;\n\n /**\n * (Optional) Executes a transactional write operation.\n * DynamoDB typically only supports this.\n *\n * @param operations - An array of write operations to perform atomically.\n * @returns True if the transaction was successful; otherwise, false.\n */\n transactWrite?(operations: any[]): Promise<boolean>;\n\n /**\n * Deletes one or more fields (attributes) from a DynamoDB item by its partition key.\n *\n * This method uses the `REMOVE` operation of the UpdateExpression to remove specific fields\n * from an existing item in the table. It dynamically constructs the expression and returns\n * the updated item (after removal).\n *\n * @param id - The value of the partition key for the item to update.\n * @param fieldNames - An array of attribute names to be removed from the item.\n * @returns The updated item as a partial object, or `undefined` if no update was performed.\n */\n deleteFields(id: string, fieldNames: string[]): Promise<Partial<T>>;\n\n /**\n * (Optional) Executes a transactional read operation.\n * DynamoDB typically only supports this.\n *\n * @param operations - An array of read operations to perform atomically.\n * @returns An array of results from the transaction.\n */\n transactRead?<TResult = any>(operations: any[]): Promise<TResult[]>;\n\n setIndexMap(value: DynamoIndexMap): boolean;\n\n getIndexMap(): DynamoIndexMap;\n\n setTable(name: string): boolean;\n\n getTableName(): string;\n\n /** Executes a DynamoDB Query strictly (requires indexName and indexValue). */\n find(filter: Filter): Promise<List<Partial<T>>>;\n\n /** Executes a DynamoDB Scan with optional non-index filters. */\n scan(filter: Filter): Promise<List<Partial<T>>>;\n\n incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n}\n"]}
|
|
@@ -223,23 +223,6 @@ class BaseRepoDBImpl {
|
|
|
223
223
|
const fieldsRemoved = (0, index_1.removeFields)(response?.items, filter.fieldsInclude, filter.fieldsExclude);
|
|
224
224
|
return { items: fieldsRemoved, lastKey: response?.lastKey };
|
|
225
225
|
}
|
|
226
|
-
async findAll(filter) {
|
|
227
|
-
if (typeof filter === "string")
|
|
228
|
-
filter = (0, index_1.parseFilter)(filter);
|
|
229
|
-
const result = [];
|
|
230
|
-
let lastKey = filter?.lastKey;
|
|
231
|
-
do {
|
|
232
|
-
const path = `${filter.urlRaw}&lastKey=${lastKey}`;
|
|
233
|
-
const itemList = await this.find((0, index_1.parseFilter)(path));
|
|
234
|
-
result.push(...itemList.items);
|
|
235
|
-
lastKey = itemList.lastKey;
|
|
236
|
-
if (result.length >= 5000) {
|
|
237
|
-
console.warn("too many items returned, breaking loop.");
|
|
238
|
-
break;
|
|
239
|
-
}
|
|
240
|
-
} while (lastKey && lastKey.trim() !== "");
|
|
241
|
-
return result;
|
|
242
|
-
}
|
|
243
226
|
async scan(filter) {
|
|
244
227
|
if (!filter)
|
|
245
228
|
filter = { size: this.DYNAMO_QUERY_LIMIT };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-db.repo.js","sourceRoot":"","sources":["../../src/repositories/base-db.repo.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAmBkC;AAClC,0DAA8D;AAC9D,oCAoBkB;AAClB,iDAA4C;AAC5C,gDAAoD;AAGpD,IAAA,gBAAO,EAAC,YAAY,CAAC,CAAC;AAEtB,MAAa,cAAc;IACR,QAAQ,GAAqB,gBAAS,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IACxE,U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AgH;QAChH,IAAI;QAEJ,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,IAAI,CAAC,kBAAkB,CAAC;QAC/C,CAAC;QAED,MAAM,OAAO,GAAG,wBAAwB,IAAI,YAAY,CAAC;QACzD,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,8BAAY,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,6BAAW,CAAC,YAAY,CAAC,CAAC;QAEzF,GAAG,CAAC,KAAK,CAAC,kBAAkB,EAAE,YAAY,CAAC,CAAC;QAE5C,IAAI,CAAC,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,sBAAa,CAAC,IAAI,CAAC,UAAU,EAAE,YAAY,EAAE,iCAAiC,CAAC,CAAC;QAE9G,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,sBAAa,CAAC,IAAI,CAAC,UAAU,EAAE,YAAY,EAAE,KAAK,CAAC,CAAC;QAChE,CAAC;IACH,CAAC;CACF;AA5mBD,wCA4mBC","sourcesContent":["import {\n AttributeValue,\n BatchGetItemCommand,\n BatchWriteItemCommand,\n BatchWriteItemCommandInput,\n DeleteItemCommand,\n GetItemCommand,\n PutItemCommand,\n QueryCommand,\n QueryCommandInput,\n QueryCommandOutput,\n ReturnValue,\n ScanCommand,\n ScanCommandInput,\n ScanCommandOutput,\n TransactWriteItemsCommand,\n TransactWriteItemsCommandInput,\n UpdateItemCommand,\n UpdateItemCommandInput,\n} from \"@aws-sdk/client-dynamodb\";\nimport { marshall, unmarshall } from \"@aws-sdk/util-dynamodb\";\nimport {\n addIndexValue,\n BaseRepoDB,\n buildDynamoDBFilterConditions,\n buildDynamoDBQueryCommand,\n buildDynamoDBScanCommand,\n buildQueryDB,\n buildUpdateExpressions,\n chunkArray,\n DBClientDynamoDB,\n DynamoIndexMap,\n generateLastEvaluatedKey,\n generateUUID,\n List,\n parseFilter,\n parseIndexFilter,\n parseLastEvaluatedKey,\n removeFields,\n toBase64,\n unMarshall,\n} from \"../index\";\nimport Container, { Service } from \"typedi\";\nimport { ErrorDynamoDB } from \"../exception/errors\";\nimport { BaseEntity, Filter } from \"@chinggis/types\";\n\nService(\"BaseRepoDB\");\n\nexport class BaseRepoDBImpl<T extends BaseEntity> implements BaseRepoDB<T> {\n private readonly dynamoDb: DBClientDynamoDB = Container.get(\"DBClientDynamoDB\");\n private _tableName: string;\n private _indexMap: DynamoIndexMap;\n private readonly DYNAMO_QUERY_LIMIT: number = 25;\n\n async deleteFields(id: string, fieldNames: string[]): Promise<Partial<T>> {\n if (!id || fieldNames.length === 0) {\n return undefined;\n }\n\n const partitionKey = this._indexMap.partitionKey;\n const expressionAttributeNames: Record<string, string> = {};\n const removeExpressions: string[] = [];\n\n for (const field of fieldNames) {\n const placeholder = `#${field}`;\n expressionAttributeNames[placeholder] = field;\n removeExpressions.push(placeholder);\n }\n\n const updateExpression = `REMOVE ${removeExpressions.join(\", \")}`;\n\n const params = {\n TableName: this._tableName,\n Key: marshall({ [partitionKey]: id }),\n UpdateExpression: updateExpression,\n ExpressionAttributeNames: expressionAttributeNames,\n ReturnValues: \"ALL_NEW\" as const,\n };\n\n const result = await this.dynamoDb.send(new UpdateItemCommand(params));\n if (!result.Attributes) {\n throw new Error(\"No attributes returned from UpdateItem.\");\n }\n\n return unmarshall(result.Attributes) as Partial<T>;\n }\n\n fieldNotExists(fieldName: string, from: number, size: number): Promise<T[]> {\n throw new Error(\"Method not implemented.\");\n }\n\n incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n if (value < 0) {\n throw new Error(\"Increment operation only supports positive values\");\n }\n\n return this.incrementOrDecrementFieldValue(entityId, fieldName, value ?? 1);\n }\n\n decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n if (value > 0) {\n throw new ErrorDynamoDB(\n this._tableName,\n `Decrement operation only supports negative values, inputValue: ${value}, for field: ${fieldName}`,\n );\n }\n return this.incrementOrDecrementFieldValue(entityId, fieldName, value ?? -1);\n }\n\n transactWrite?(operations: any[]): Promise<boolean> {\n throw new Error(\"Method not implemented.\");\n }\n\n async update(entity: Partial<T>): Promise<T> {\n const partitionKey = this._indexMap.partitionKey;\n\n if (!entity[partitionKey]) {\n throw new ErrorDynamoDB(this._tableName, `Entity must have value in field ${partitionKey}`);\n }\n\n const indexedItem = addIndexValue(entity, this._indexMap);\n\n const { UpdateExpression, ExpressionAttributeNames, ExpressionAttributeValues } = buildUpdateExpressions(\n indexedItem,\n [partitionKey],\n );\n\n const params = {\n TableName: this._tableName,\n Key: marshall({ [partitionKey]: indexedItem[partitionKey] }),\n UpdateExpression,\n ExpressionAttributeNames,\n ExpressionAttributeValues,\n ReturnValues: ReturnValue.ALL_NEW,\n };\n\n const result = await this.dynamoDb.send(new UpdateItemCommand(params));\n if (!result.Attributes) {\n throw new Error(\"No attributes returned from UpdateItem.\");\n }\n return unmarshall(result.Attributes) as T;\n }\n\n async updateMany(entityList: Partial<T>[], fields: string[], isTransactional: boolean): Promise<boolean> {\n if (isTransactional === undefined || isTransactional === false || isTransactional === null)\n return await this.updateManyNormal(entityList, fields);\n\n return await this.updateManyTransactional(entityList, fields);\n }\n\n async save(entity: Partial<T>): Promise<T> {\n const partitionKey = this._indexMap.partitionKey;\n\n if (!entity[partitionKey]) throw new Error(`Entity must have a ${partitionKey} field.`);\n\n const indexedItem = addIndexValue(entity, this._indexMap);\n\n const params = {\n TableName: this._tableName,\n Item: marshall(indexedItem, { removeUndefinedValues: true }),\n };\n try {\n await this.dynamoDb.send(new PutItemCommand(params));\n\n return entity as T;\n } catch (error) {\n console.error(\"Error saving entity:\", error);\n throw new ErrorDynamoDB(this._tableName, params, error);\n }\n }\n\n async saveMany(entities: Partial<T>[], isTransactional?: boolean): Promise<Partial<T>[]> {\n if (isTransactional === undefined || isTransactional === null || isTransactional === false)\n return await this.saveManyNormal(entities);\n return await this.saveManyTransactional(entities);\n }\n\n async delete(id: string): Promise<boolean> {\n const params = {\n TableName: this._tableName,\n Key: marshall({ [this._indexMap.partitionKey]: id }),\n };\n\n try {\n await this.dynamoDb.send(new DeleteItemCommand(params));\n return true;\n } catch (error) {\n console.error(\"Error deleting item:\", error);\n throw new ErrorDynamoDB(this._tableName, params, error);\n }\n }\n\n async deleteMany(ids: string[]): Promise<boolean> {\n if (ids?.length === 0) return false;\n const chunked = chunkArray(ids, 25);\n for (const chunk of chunked) {\n const deleteRequests = chunk.map((id) => {\n return {\n DeleteRequest: {\n Key: marshall({ [this._indexMap.partitionKey]: id }),\n },\n };\n });\n\n const params = {\n RequestItems: {\n [this._tableName]: deleteRequests,\n },\n };\n\n await this.dynamoDb.send(new BatchWriteItemCommand(params));\n }\n return true;\n }\n\n async findById(id: string): Promise<T> {\n const params = {\n TableName: this._tableName,\n Key: marshall({ [this._indexMap.partitionKey]: id }),\n };\n\n try {\n const result = await this.dynamoDb.send(new GetItemCommand(params));\n if (!result.Item) return null;\n return unmarshall(result.Item) as T;\n } catch (error) {\n console.error(\"Error getting item:\", error);\n throw new ErrorDynamoDB(this._tableName, params, error);\n }\n }\n\n async findByIds(ids: string[]): Promise<T[]> {\n let items: T[] = [];\n if (!ids || ids.length === 0) throw new Error(\"Item must have entityIds\");\n\n const chunked = chunkArray(ids, 100);\n for (const chunk of chunked) {\n const keys = chunk.map((id) => ({ [this._indexMap.partitionKey]: { S: id } }));\n const params = {\n RequestItems: {\n [this._tableName]: { Keys: keys },\n },\n };\n\n const response = await this.dynamoDb.send(new BatchGetItemCommand(params));\n\n items = items.concat(response.Responses?.[this._tableName]?.map((item) => unmarshall(item)) as T[]) ?? [];\n }\n return items;\n }\n\n async find(filter: Filter): Promise<List<Partial<T>>> {\n if (!filter) filter = { size: this.DYNAMO_QUERY_LIMIT };\n\n // Enforce Query-only: require indexName & indexValue; otherwise instruct the caller to use scan\n if (!filter.indexName || filter.indexValue === undefined || filter.indexValue === null) {\n throw new ErrorDynamoDB(\n this._tableName,\n \"find in by index\",\n \"find requires indexName and indexValue; use scan() otherwise\",\n );\n }\n\n const dbQuery = buildDynamoDBQueryCommand({\n tableName: this._tableName,\n filter,\n filterCondition: buildDynamoDBFilterConditions(filter, this._indexMap),\n indexMap: this._indexMap,\n });\n\n const response = await this.sendCommandDeep<T>(dbQuery, filter?.lastKey);\n const fieldsRemoved = removeFields(response?.items, filter.fieldsInclude, filter.fieldsExclude);\n return { items: fieldsRemoved, lastKey: response?.lastKey };\n }\n\n async findAll(filter: Filter | string): Promise<Partial<T>[]> {\n if (typeof filter === \"string\") filter = parseFilter(filter);\n const result: Partial<T>[] = [];\n let lastKey = filter?.lastKey;\n\n do {\n const path = `${filter.urlRaw}&lastKey=${lastKey}`;\n const itemList = await this.find(parseFilter(path));\n\n result.push(...itemList.items);\n lastKey = itemList.lastKey;\n\n if (result.length >= 5000) {\n console.warn(\"too many items returned, breaking loop.\");\n break;\n }\n } while (lastKey && lastKey.trim() !== \"\");\n\n return result;\n }\n\n async scan(filter: Filter): Promise<List<Partial<T>>> {\n if (!filter) filter = { size: this.DYNAMO_QUERY_LIMIT };\n const expression = buildDynamoDBFilterConditions(filter, this._indexMap);\n const scanInput = buildDynamoDBScanCommand({ tableName: this._tableName, filter, expression });\n const response = await this.sendCommandDeep<T>(scanInput, filter?.lastKey);\n const fieldsRemoved = removeFields(response?.items, filter.fieldsInclude, filter.fieldsExclude);\n return { items: fieldsRemoved, lastKey: response?.lastKey };\n }\n\n async findOne(filter: Filter): Promise<T> {\n const queryInput = buildQueryDB(this._tableName, filter, this._indexMap);\n queryInput.Limit = 1;\n\n const result = await this.dynamoDb.send(new QueryCommand(queryInput));\n\n if (!result.Items || result.Items.length === 0) return null;\n return unmarshall(result.Items[0]) as T;\n }\n\n findByIndex(indexName: string, value: string): Promise<List<Partial<T>>> {\n return this.find(parseIndexFilter(indexName + \"=\" + value, this._indexMap));\n }\n\n async count(filter: Filter): Promise<number> {\n const queryInput = buildQueryDB(this._tableName, filter, this._indexMap);\n queryInput.Select = \"COUNT\";\n\n const result = await this.dynamoDb.send(new QueryCommand(queryInput));\n return result.Count ?? 0;\n }\n\n async exists(id: string): Promise<boolean> {\n const key = marshall({ [this._indexMap.partitionKey]: id });\n\n const result = await this.dynamoDb.send(\n new GetItemCommand({\n TableName: this._tableName,\n Key: key,\n ProjectionExpression: this._indexMap.partitionKey,\n }),\n );\n\n return !!result.Item;\n }\n\n async getRaw(filter: Filter): Promise<any> {\n const queryInput = buildQueryDB(this._tableName, filter, this._indexMap);\n return this.dynamoDb.send(new QueryCommand(queryInput));\n }\n\n async transactionRead<T>(operations: { id: string; sortKey?: string }[]): Promise<T[]> {\n throw new Error(\"Method not implemented.\");\n }\n\n async transactRead?<TResult = any>(operations: any[]): Promise<TResult[]> {\n throw new Error(\"Method not implemented.\");\n }\n\n async transactionWrite(operations: {\n create?: { tableName: string; item: Record<string, any> }[];\n update?: {\n tableName: string;\n key: { id: string };\n updateData: Record<string, any>;\n }[];\n delete?: { tableName: string; key: { id: string } }[];\n }): Promise<boolean> {\n const transactItems: any[] = [];\n\n // Create operations\n if (operations.create) {\n for (const { tableName, item } of operations.create) {\n if (!item?.id) {\n item.id = generateUUID();\n }\n transactItems.push({\n Put: {\n TableName: tableName,\n Item: marshall(item, { removeUndefinedValues: true }),\n },\n });\n }\n }\n\n // Update operations\n if (operations.update) {\n for (const { tableName, key, updateData } of operations.update) {\n const { UpdateExpression, ExpressionAttributeNames, ExpressionAttributeValues } = buildUpdateExpressions(\n updateData,\n [\"id\"],\n );\n\n transactItems.push({\n Update: {\n TableName: tableName,\n Key: marshall(key),\n UpdateExpression,\n ExpressionAttributeNames,\n ExpressionAttributeValues,\n },\n });\n }\n }\n\n // Delete operations\n if (operations.delete) {\n for (const { tableName, key } of operations.delete) {\n transactItems.push({\n Delete: {\n TableName: tableName,\n Key: marshall(key),\n },\n });\n }\n }\n\n if (transactItems.length === 0) return false;\n\n // Execute transaction\n try {\n await this.dynamoDb.send(new TransactWriteItemsCommand({ TransactItems: transactItems }));\n return true;\n } catch (error) {\n console.error(\"Transaction failed:\", error);\n throw new ErrorDynamoDB(this._tableName, transactItems, error);\n }\n }\n\n getTableName() {\n return this._tableName;\n }\n\n setIndexMap(indexMap: DynamoIndexMap): boolean {\n this._indexMap = indexMap;\n return true;\n }\n\n setTable(tableName: string): boolean {\n this._tableName = tableName;\n return true;\n }\n\n getIndexMap(): DynamoIndexMap {\n return this._indexMap;\n }\n\n private async updateManyNormal(entityList: Partial<T>[], fieldNames: string[]): Promise<boolean> {\n return this.updateManyTransactional(entityList, fieldNames); // todo implement normal updateMany\n }\n\n private async updateManyTransactional(entityList: Partial<T>[], fieldNames: string[]): Promise<boolean> {\n if (entityList.length === 0) return false;\n\n if (!fieldNames || fieldNames.length === 0) {\n await this.saveMany(entityList, true);\n return true;\n }\n\n const partitionKey = this._indexMap.partitionKey;\n fieldNames.push(partitionKey);\n const entityListCleaned = removeFields(entityList, fieldNames);\n\n const indexedItems = entityListCleaned.map((entity) => {\n return addIndexValue(entity, this._indexMap);\n });\n\n const transactItems = indexedItems\n .map((item) => {\n if (!item[partitionKey])\n throw new Error(\n `Item must have an ${partitionKey} field. Entity: ${JSON.stringify(item, null, 2)}, \\nupdateFields: ${JSON.stringify(fieldNames)}`,\n );\n\n const { UpdateExpression, ExpressionAttributeNames, ExpressionAttributeValues } = buildUpdateExpressions(item, [\n partitionKey,\n ]);\n\n return {\n Update: {\n TableName: this._tableName,\n Key: { [partitionKey]: { S: item[partitionKey] } }, // id-г шууд key болгож дамжуулах\n UpdateExpression,\n ExpressionAttributeValues,\n ExpressionAttributeNames,\n },\n };\n })\n .filter(Boolean) as any[]; // filter(Boolean) нь хоосон утгуудыг арилгана.\n\n if (transactItems.length < 1) return false;\n\n const chunkedItems = chunkArray(transactItems, 25); // 25-аас дээш бол багцлах\n\n for (const chunk of chunkedItems) await this.dynamoDb.send(new TransactWriteItemsCommand({ TransactItems: chunk }));\n\n return true;\n }\n\n private async saveManyNormal(entities: Partial<T>[]): Promise<Partial<T>[]> {\n if (entities.length === 0) throw new Error(\"Cannot save an empty array of entities.\");\n\n const allSavedEntities: Partial<T>[] = [];\n\n for (const chunk of chunkArray(entities, 25)) {\n chunk.forEach((item) => addIndexValue(item, this._indexMap));\n const putRequests = chunk.map((entity) => ({\n PutRequest: { Item: marshall(entity, { removeUndefinedValues: true }) },\n }));\n\n const params: BatchWriteItemCommandInput = { RequestItems: { [this._tableName]: putRequests } };\n\n const result = await this.dynamoDb.send(new BatchWriteItemCommand(params));\n\n if (result.UnprocessedItems && Object.keys(result.UnprocessedItems).length > 0)\n console.warn(\"⚠️ Some items were unprocessed and need to be retried.\", result.UnprocessedItems);\n\n allSavedEntities.push(...chunk);\n }\n\n return allSavedEntities;\n }\n\n private async saveManyTransactional(entities: Partial<T>[]): Promise<Partial<T>[]> {\n if (entities.length === 0) throw new Error(\"Cannot save an empty array of entities.\");\n\n const allSavedEntities: Partial<T>[] = [];\n\n // DynamoDB TransactWrite limit: 25 actions per request\n for (const chunk of chunkArray(entities, 25)) {\n chunk.forEach((item) => addIndexValue(item, this._indexMap));\n\n const transactItems = chunk.map((entity) => ({\n Put: {\n TableName: this._tableName,\n Item: marshall(entity, { removeUndefinedValues: true }),\n },\n }));\n\n const params: TransactWriteItemsCommandInput = {\n TransactItems: transactItems,\n };\n\n try {\n await this.dynamoDb.send(new TransactWriteItemsCommand(params));\n allSavedEntities.push(...chunk);\n } catch (err) {\n console.error(\"❌ Transaction failed:\", err);\n throw err; // Re-throw so the caller knows it failed\n }\n }\n\n return allSavedEntities;\n }\n\n private async incrementOrDecrementFieldValue(entityId: string, fieldName: string, delta: number): Promise<T> {\n const partitionKey = this._indexMap.partitionKey;\n if (!this?._indexMap?.numberFields?.includes(fieldName)) {\n throw new Error(`${fieldName} field not found in indexMap.numberFields`);\n }\n\n const params: UpdateItemCommandInput = {\n TableName: this._tableName,\n Key: marshall({ [partitionKey]: entityId }),\n UpdateExpression: `SET #field = if_not_exists(#field, :start) + :delta`,\n ExpressionAttributeNames: {\n \"#field\": fieldName,\n },\n ExpressionAttributeValues: {\n \":delta\": marshall(delta),\n \":start\": marshall(0),\n },\n ReturnValues: ReturnValue.ALL_NEW,\n };\n\n const result = await this.dynamoDb.send(new UpdateItemCommand(params));\n\n return unmarshall(result.Attributes) as T;\n }\n\n /**\n * Executes a DynamoDB Query or Scan and returns up to the desired number of items,\n * respecting DynamoDB's 1MB limit (pagination continuation via LastEvaluatedKey).\n * @param queryInput - QueryCommandInput or ScanCommandInput\n * @param startKey - Optional start key for pagination\n */\n\n private async sendCommandDeep<T>(\n queryInput: QueryCommandInput | ScanCommandInput,\n startKey?: string | Record<string, any>,\n ): Promise<List<T>> {\n const result: List<T> = { items: [] };\n\n const size: number = (queryInput as any)?.Limit ?? 10;\n\n let lastEvaluatedKey: Record<string, AttributeValue>;\n\n if (startKey) {\n lastEvaluatedKey =\n typeof startKey === \"string\"\n ? parseLastEvaluatedKey<Record<string, AttributeValue>>(startKey) // will throw if invalid\n : startKey;\n }\n\n do {\n const response: QueryCommandOutput = await this.sendCommand({\n ...queryInput,\n ExclusiveStartKey: lastEvaluatedKey,\n });\n\n // no more items to fetch\n if (response.LastEvaluatedKey == undefined) {\n result?.items.push(...unMarshall<T>(response.Items));\n result.lastKey = undefined;\n return result;\n }\n\n if (response?.Items.length === 0 && response.LastEvaluatedKey) {\n lastEvaluatedKey = response.LastEvaluatedKey;\n continue;\n }\n\n if (result?.items.length + response?.Items.length <= size) {\n result?.items.push(...unMarshall<T>(response.Items));\n lastEvaluatedKey = response.LastEvaluatedKey;\n if (result?.items.length === size) {\n result.lastKey = toBase64(JSON.stringify(response.LastEvaluatedKey));\n return result;\n }\n continue;\n }\n\n const elementIndex = size - result?.items.length - 1;\n result?.items.push(...unMarshall<T>(response.Items.slice(0, elementIndex)));\n\n const index = this._indexMap.get(queryInput.IndexName);\n result.lastKey = generateLastEvaluatedKey(response.Items[elementIndex], index?.field, index?.sortKeyField);\n break;\n } while (lastEvaluatedKey);\n\n return result;\n }\n\n /**\n * Executes a single Query/Scan and returns the result as-is.\n * Supports pagination via ExclusiveStartKey.\n */\n private async sendCommand(\n commandInput: QueryCommandInput | ScanCommandInput,\n ): Promise<ScanCommandOutput | QueryCommandOutput> {\n commandInput.TableName = this._tableName;\n\n // if (startKey) {\n // commandInput.ExclusiveStartKey = typeof startKey === \"string\" ? parseLastEvaluatedKey(startKey) : startKey;\n // }\n\n if (!commandInput.Limit) {\n commandInput.Limit = this.DYNAMO_QUERY_LIMIT;\n }\n\n const isQuery = \"KeyConditionExpression\" in commandInput;\n const command = isQuery ? new QueryCommand(commandInput) : new ScanCommand(commandInput);\n\n log.debug(\"Sending command:\", commandInput);\n\n if (!this.dynamoDb) throw new ErrorDynamoDB(this._tableName, commandInput, \"dynamoDB client not initialized\");\n\n try {\n return await this.dynamoDb.send(command);\n } catch (error) {\n throw new ErrorDynamoDB(this._tableName, commandInput, error);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base-db.repo.js","sourceRoot":"","sources":["../../src/repositories/base-db.repo.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAmBkC;AAClC,0DAA8D;AAC9D,oCAmBkB;AAClB,iDAA4C;AAC5C,gDAAoD;AAGpD,IAAA,gBAAO,EAAC,YAAY,CAAC,CAAC;AAEtB,MAAa,cAAc;IACR,QAAQ,GAAqB,gBAAS,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IACxE,UAAU,CAAS;IACnB,SAAS,CAAiB;IACjB,kBAAkB,GAAW,EAAE,CAAC;IAEjD,KAAK,CAAC,YAAY,CAAC,EAAU,EAAE,UAAoB;QACjD,IAAI,CAAC,EAAE,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACnC,OAAO,SAAS,CAAC;QACnB,CAAC;Q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K,EAAE,KAAK,EAAE,YAAY,CAAC,CAAC;YAC3G,MAAM;QACR,CAAC,QAAQ,gBAAgB,EAAE;QAE3B,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;OAGG;IACK,KAAK,CAAC,WAAW,CACvB,YAAkD;QAElD,YAAY,CAAC,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC;QAEzC,kBAAkB;QAClB,gHAAgH;QAChH,IAAI;QAEJ,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,IAAI,CAAC,kBAAkB,CAAC;QAC/C,CAAC;QAED,MAAM,OAAO,GAAG,wBAAwB,IAAI,YAAY,CAAC;QACzD,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,8BAAY,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,6BAAW,CAAC,YAAY,CAAC,CAAC;QAEzF,GAAG,CAAC,KAAK,CAAC,kBAAkB,EAAE,YAAY,CAAC,CAAC;QAE5C,IAAI,CAAC,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,sBAAa,CAAC,IAAI,CAAC,UAAU,EAAE,YAAY,EAAE,iCAAiC,CAAC,CAAC;QAE9G,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,sBAAa,CAAC,IAAI,CAAC,UAAU,EAAE,YAAY,EAAE,KAAK,CAAC,CAAC;QAChE,CAAC;IACH,CAAC;CACF;AAvlBD,wCAulBC","sourcesContent":["import {\n AttributeValue,\n BatchGetItemCommand,\n BatchWriteItemCommand,\n BatchWriteItemCommandInput,\n DeleteItemCommand,\n GetItemCommand,\n PutItemCommand,\n QueryCommand,\n QueryCommandInput,\n QueryCommandOutput,\n ReturnValue,\n ScanCommand,\n ScanCommandInput,\n ScanCommandOutput,\n TransactWriteItemsCommand,\n TransactWriteItemsCommandInput,\n UpdateItemCommand,\n UpdateItemCommandInput,\n} from \"@aws-sdk/client-dynamodb\";\nimport { marshall, unmarshall } from \"@aws-sdk/util-dynamodb\";\nimport {\n addIndexValue,\n BaseRepoDB,\n buildDynamoDBFilterConditions,\n buildDynamoDBQueryCommand,\n buildDynamoDBScanCommand,\n buildQueryDB,\n buildUpdateExpressions,\n chunkArray,\n DBClientDynamoDB,\n DynamoIndexMap,\n generateLastEvaluatedKey,\n generateUUID,\n List,\n parseIndexFilter,\n parseLastEvaluatedKey,\n removeFields,\n toBase64,\n unMarshall,\n} from \"../index\";\nimport Container, { Service } from \"typedi\";\nimport { ErrorDynamoDB } from \"../exception/errors\";\nimport { BaseEntity, Filter } from \"@chinggis/types\";\n\nService(\"BaseRepoDB\");\n\nexport class BaseRepoDBImpl<T extends BaseEntity> implements BaseRepoDB<T> {\n private readonly dynamoDb: DBClientDynamoDB = Container.get(\"DBClientDynamoDB\");\n private _tableName: string;\n private _indexMap: DynamoIndexMap;\n private readonly DYNAMO_QUERY_LIMIT: number = 25;\n\n async deleteFields(id: string, fieldNames: string[]): Promise<Partial<T>> {\n if (!id || fieldNames.length === 0) {\n return undefined;\n }\n\n const partitionKey = this._indexMap.partitionKey;\n const expressionAttributeNames: Record<string, string> = {};\n const removeExpressions: string[] = [];\n\n for (const field of fieldNames) {\n const placeholder = `#${field}`;\n expressionAttributeNames[placeholder] = field;\n removeExpressions.push(placeholder);\n }\n\n const updateExpression = `REMOVE ${removeExpressions.join(\", \")}`;\n\n const params = {\n TableName: this._tableName,\n Key: marshall({ [partitionKey]: id }),\n UpdateExpression: updateExpression,\n ExpressionAttributeNames: expressionAttributeNames,\n ReturnValues: \"ALL_NEW\" as const,\n };\n\n const result = await this.dynamoDb.send(new UpdateItemCommand(params));\n if (!result.Attributes) {\n throw new Error(\"No attributes returned from UpdateItem.\");\n }\n\n return unmarshall(result.Attributes) as Partial<T>;\n }\n\n fieldNotExists(fieldName: string, from: number, size: number): Promise<T[]> {\n throw new Error(\"Method not implemented.\");\n }\n\n incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n if (value < 0) {\n throw new Error(\"Increment operation only supports positive values\");\n }\n\n return this.incrementOrDecrementFieldValue(entityId, fieldName, value ?? 1);\n }\n\n decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n if (value > 0) {\n throw new ErrorDynamoDB(\n this._tableName,\n `Decrement operation only supports negative values, inputValue: ${value}, for field: ${fieldName}`,\n );\n }\n return this.incrementOrDecrementFieldValue(entityId, fieldName, value ?? -1);\n }\n\n transactWrite?(operations: any[]): Promise<boolean> {\n throw new Error(\"Method not implemented.\");\n }\n\n async update(entity: Partial<T>): Promise<T> {\n const partitionKey = this._indexMap.partitionKey;\n\n if (!entity[partitionKey]) {\n throw new ErrorDynamoDB(this._tableName, `Entity must have value in field ${partitionKey}`);\n }\n\n const indexedItem = addIndexValue(entity, this._indexMap);\n\n const { UpdateExpression, ExpressionAttributeNames, ExpressionAttributeValues } = buildUpdateExpressions(\n indexedItem,\n [partitionKey],\n );\n\n const params = {\n TableName: this._tableName,\n Key: marshall({ [partitionKey]: indexedItem[partitionKey] }),\n UpdateExpression,\n ExpressionAttributeNames,\n ExpressionAttributeValues,\n ReturnValues: ReturnValue.ALL_NEW,\n };\n\n const result = await this.dynamoDb.send(new UpdateItemCommand(params));\n if (!result.Attributes) {\n throw new Error(\"No attributes returned from UpdateItem.\");\n }\n return unmarshall(result.Attributes) as T;\n }\n\n async updateMany(entityList: Partial<T>[], fields: string[], isTransactional: boolean): Promise<boolean> {\n if (isTransactional === undefined || isTransactional === false || isTransactional === null)\n return await this.updateManyNormal(entityList, fields);\n\n return await this.updateManyTransactional(entityList, fields);\n }\n\n async save(entity: Partial<T>): Promise<T> {\n const partitionKey = this._indexMap.partitionKey;\n\n if (!entity[partitionKey]) throw new Error(`Entity must have a ${partitionKey} field.`);\n\n const indexedItem = addIndexValue(entity, this._indexMap);\n\n const params = {\n TableName: this._tableName,\n Item: marshall(indexedItem, { removeUndefinedValues: true }),\n };\n try {\n await this.dynamoDb.send(new PutItemCommand(params));\n\n return entity as T;\n } catch (error) {\n console.error(\"Error saving entity:\", error);\n throw new ErrorDynamoDB(this._tableName, params, error);\n }\n }\n\n async saveMany(entities: Partial<T>[], isTransactional?: boolean): Promise<Partial<T>[]> {\n if (isTransactional === undefined || isTransactional === null || isTransactional === false)\n return await this.saveManyNormal(entities);\n return await this.saveManyTransactional(entities);\n }\n\n async delete(id: string): Promise<boolean> {\n const params = {\n TableName: this._tableName,\n Key: marshall({ [this._indexMap.partitionKey]: id }),\n };\n\n try {\n await this.dynamoDb.send(new DeleteItemCommand(params));\n return true;\n } catch (error) {\n console.error(\"Error deleting item:\", error);\n throw new ErrorDynamoDB(this._tableName, params, error);\n }\n }\n\n async deleteMany(ids: string[]): Promise<boolean> {\n if (ids?.length === 0) return false;\n const chunked = chunkArray(ids, 25);\n for (const chunk of chunked) {\n const deleteRequests = chunk.map((id) => {\n return {\n DeleteRequest: {\n Key: marshall({ [this._indexMap.partitionKey]: id }),\n },\n };\n });\n\n const params = {\n RequestItems: {\n [this._tableName]: deleteRequests,\n },\n };\n\n await this.dynamoDb.send(new BatchWriteItemCommand(params));\n }\n return true;\n }\n\n async findById(id: string): Promise<T> {\n const params = {\n TableName: this._tableName,\n Key: marshall({ [this._indexMap.partitionKey]: id }),\n };\n\n try {\n const result = await this.dynamoDb.send(new GetItemCommand(params));\n if (!result.Item) return null;\n return unmarshall(result.Item) as T;\n } catch (error) {\n console.error(\"Error getting item:\", error);\n throw new ErrorDynamoDB(this._tableName, params, error);\n }\n }\n\n async findByIds(ids: string[]): Promise<T[]> {\n let items: T[] = [];\n if (!ids || ids.length === 0) throw new Error(\"Item must have entityIds\");\n\n const chunked = chunkArray(ids, 100);\n for (const chunk of chunked) {\n const keys = chunk.map((id) => ({ [this._indexMap.partitionKey]: { S: id } }));\n const params = {\n RequestItems: {\n [this._tableName]: { Keys: keys },\n },\n };\n\n const response = await this.dynamoDb.send(new BatchGetItemCommand(params));\n\n items = items.concat(response.Responses?.[this._tableName]?.map((item) => unmarshall(item)) as T[]) ?? [];\n }\n return items;\n }\n\n async find(filter: Filter): Promise<List<Partial<T>>> {\n if (!filter) filter = { size: this.DYNAMO_QUERY_LIMIT };\n\n // Enforce Query-only: require indexName & indexValue; otherwise instruct the caller to use scan\n if (!filter.indexName || filter.indexValue === undefined || filter.indexValue === null) {\n throw new ErrorDynamoDB(\n this._tableName,\n \"find in by index\",\n \"find requires indexName and indexValue; use scan() otherwise\",\n );\n }\n\n const dbQuery = buildDynamoDBQueryCommand({\n tableName: this._tableName,\n filter,\n filterCondition: buildDynamoDBFilterConditions(filter, this._indexMap),\n indexMap: this._indexMap,\n });\n\n const response = await this.sendCommandDeep<T>(dbQuery, filter?.lastKey);\n const fieldsRemoved = removeFields(response?.items, filter.fieldsInclude, filter.fieldsExclude);\n return { items: fieldsRemoved, lastKey: response?.lastKey };\n }\n\n async scan(filter: Filter): Promise<List<Partial<T>>> {\n if (!filter) filter = { size: this.DYNAMO_QUERY_LIMIT };\n const expression = buildDynamoDBFilterConditions(filter, this._indexMap);\n const scanInput = buildDynamoDBScanCommand({ tableName: this._tableName, filter, expression });\n const response = await this.sendCommandDeep<T>(scanInput, filter?.lastKey);\n const fieldsRemoved = removeFields(response?.items, filter.fieldsInclude, filter.fieldsExclude);\n return { items: fieldsRemoved, lastKey: response?.lastKey };\n }\n\n async findOne(filter: Filter): Promise<T> {\n const queryInput = buildQueryDB(this._tableName, filter, this._indexMap);\n queryInput.Limit = 1;\n\n const result = await this.dynamoDb.send(new QueryCommand(queryInput));\n\n if (!result.Items || result.Items.length === 0) return null;\n return unmarshall(result.Items[0]) as T;\n }\n\n findByIndex(indexName: string, value: string): Promise<List<Partial<T>>> {\n return this.find(parseIndexFilter(indexName + \"=\" + value, this._indexMap));\n }\n\n async count(filter: Filter): Promise<number> {\n const queryInput = buildQueryDB(this._tableName, filter, this._indexMap);\n queryInput.Select = \"COUNT\";\n\n const result = await this.dynamoDb.send(new QueryCommand(queryInput));\n return result.Count ?? 0;\n }\n\n async exists(id: string): Promise<boolean> {\n const key = marshall({ [this._indexMap.partitionKey]: id });\n\n const result = await this.dynamoDb.send(\n new GetItemCommand({\n TableName: this._tableName,\n Key: key,\n ProjectionExpression: this._indexMap.partitionKey,\n }),\n );\n\n return !!result.Item;\n }\n\n async getRaw(filter: Filter): Promise<any> {\n const queryInput = buildQueryDB(this._tableName, filter, this._indexMap);\n return this.dynamoDb.send(new QueryCommand(queryInput));\n }\n\n async transactionRead<T>(operations: { id: string; sortKey?: string }[]): Promise<T[]> {\n throw new Error(\"Method not implemented.\");\n }\n\n async transactRead?<TResult = any>(operations: any[]): Promise<TResult[]> {\n throw new Error(\"Method not implemented.\");\n }\n\n async transactionWrite(operations: {\n create?: { tableName: string; item: Record<string, any> }[];\n update?: {\n tableName: string;\n key: { id: string };\n updateData: Record<string, any>;\n }[];\n delete?: { tableName: string; key: { id: string } }[];\n }): Promise<boolean> {\n const transactItems: any[] = [];\n\n // Create operations\n if (operations.create) {\n for (const { tableName, item } of operations.create) {\n if (!item?.id) {\n item.id = generateUUID();\n }\n transactItems.push({\n Put: {\n TableName: tableName,\n Item: marshall(item, { removeUndefinedValues: true }),\n },\n });\n }\n }\n\n // Update operations\n if (operations.update) {\n for (const { tableName, key, updateData } of operations.update) {\n const { UpdateExpression, ExpressionAttributeNames, ExpressionAttributeValues } = buildUpdateExpressions(\n updateData,\n [\"id\"],\n );\n\n transactItems.push({\n Update: {\n TableName: tableName,\n Key: marshall(key),\n UpdateExpression,\n ExpressionAttributeNames,\n ExpressionAttributeValues,\n },\n });\n }\n }\n\n // Delete operations\n if (operations.delete) {\n for (const { tableName, key } of operations.delete) {\n transactItems.push({\n Delete: {\n TableName: tableName,\n Key: marshall(key),\n },\n });\n }\n }\n\n if (transactItems.length === 0) return false;\n\n // Execute transaction\n try {\n await this.dynamoDb.send(new TransactWriteItemsCommand({ TransactItems: transactItems }));\n return true;\n } catch (error) {\n console.error(\"Transaction failed:\", error);\n throw new ErrorDynamoDB(this._tableName, transactItems, error);\n }\n }\n\n getTableName() {\n return this._tableName;\n }\n\n setIndexMap(indexMap: DynamoIndexMap): boolean {\n this._indexMap = indexMap;\n return true;\n }\n\n setTable(tableName: string): boolean {\n this._tableName = tableName;\n return true;\n }\n\n getIndexMap(): DynamoIndexMap {\n return this._indexMap;\n }\n\n private async updateManyNormal(entityList: Partial<T>[], fieldNames: string[]): Promise<boolean> {\n return this.updateManyTransactional(entityList, fieldNames); // todo implement normal updateMany\n }\n\n private async updateManyTransactional(entityList: Partial<T>[], fieldNames: string[]): Promise<boolean> {\n if (entityList.length === 0) return false;\n\n if (!fieldNames || fieldNames.length === 0) {\n await this.saveMany(entityList, true);\n return true;\n }\n\n const partitionKey = this._indexMap.partitionKey;\n fieldNames.push(partitionKey);\n const entityListCleaned = removeFields(entityList, fieldNames);\n\n const indexedItems = entityListCleaned.map((entity) => {\n return addIndexValue(entity, this._indexMap);\n });\n\n const transactItems = indexedItems\n .map((item) => {\n if (!item[partitionKey])\n throw new Error(\n `Item must have an ${partitionKey} field. Entity: ${JSON.stringify(item, null, 2)}, \\nupdateFields: ${JSON.stringify(fieldNames)}`,\n );\n\n const { UpdateExpression, ExpressionAttributeNames, ExpressionAttributeValues } = buildUpdateExpressions(item, [\n partitionKey,\n ]);\n\n return {\n Update: {\n TableName: this._tableName,\n Key: { [partitionKey]: { S: item[partitionKey] } }, // id-г шууд key болгож дамжуулах\n UpdateExpression,\n ExpressionAttributeValues,\n ExpressionAttributeNames,\n },\n };\n })\n .filter(Boolean) as any[]; // filter(Boolean) нь хоосон утгуудыг арилгана.\n\n if (transactItems.length < 1) return false;\n\n const chunkedItems = chunkArray(transactItems, 25); // 25-аас дээш бол багцлах\n\n for (const chunk of chunkedItems) await this.dynamoDb.send(new TransactWriteItemsCommand({ TransactItems: chunk }));\n\n return true;\n }\n\n private async saveManyNormal(entities: Partial<T>[]): Promise<Partial<T>[]> {\n if (entities.length === 0) throw new Error(\"Cannot save an empty array of entities.\");\n\n const allSavedEntities: Partial<T>[] = [];\n\n for (const chunk of chunkArray(entities, 25)) {\n chunk.forEach((item) => addIndexValue(item, this._indexMap));\n const putRequests = chunk.map((entity) => ({\n PutRequest: { Item: marshall(entity, { removeUndefinedValues: true }) },\n }));\n\n const params: BatchWriteItemCommandInput = { RequestItems: { [this._tableName]: putRequests } };\n\n const result = await this.dynamoDb.send(new BatchWriteItemCommand(params));\n\n if (result.UnprocessedItems && Object.keys(result.UnprocessedItems).length > 0)\n console.warn(\"⚠️ Some items were unprocessed and need to be retried.\", result.UnprocessedItems);\n\n allSavedEntities.push(...chunk);\n }\n\n return allSavedEntities;\n }\n\n private async saveManyTransactional(entities: Partial<T>[]): Promise<Partial<T>[]> {\n if (entities.length === 0) throw new Error(\"Cannot save an empty array of entities.\");\n\n const allSavedEntities: Partial<T>[] = [];\n\n // DynamoDB TransactWrite limit: 25 actions per request\n for (const chunk of chunkArray(entities, 25)) {\n chunk.forEach((item) => addIndexValue(item, this._indexMap));\n\n const transactItems = chunk.map((entity) => ({\n Put: {\n TableName: this._tableName,\n Item: marshall(entity, { removeUndefinedValues: true }),\n },\n }));\n\n const params: TransactWriteItemsCommandInput = {\n TransactItems: transactItems,\n };\n\n try {\n await this.dynamoDb.send(new TransactWriteItemsCommand(params));\n allSavedEntities.push(...chunk);\n } catch (err) {\n console.error(\"❌ Transaction failed:\", err);\n throw err; // Re-throw so the caller knows it failed\n }\n }\n\n return allSavedEntities;\n }\n\n private async incrementOrDecrementFieldValue(entityId: string, fieldName: string, delta: number): Promise<T> {\n const partitionKey = this._indexMap.partitionKey;\n if (!this?._indexMap?.numberFields?.includes(fieldName)) {\n throw new Error(`${fieldName} field not found in indexMap.numberFields`);\n }\n\n const params: UpdateItemCommandInput = {\n TableName: this._tableName,\n Key: marshall({ [partitionKey]: entityId }),\n UpdateExpression: `SET #field = if_not_exists(#field, :start) + :delta`,\n ExpressionAttributeNames: {\n \"#field\": fieldName,\n },\n ExpressionAttributeValues: {\n \":delta\": marshall(delta),\n \":start\": marshall(0),\n },\n ReturnValues: ReturnValue.ALL_NEW,\n };\n\n const result = await this.dynamoDb.send(new UpdateItemCommand(params));\n\n return unmarshall(result.Attributes) as T;\n }\n\n /**\n * Executes a DynamoDB Query or Scan and returns up to the desired number of items,\n * respecting DynamoDB's 1MB limit (pagination continuation via LastEvaluatedKey).\n * @param queryInput - QueryCommandInput or ScanCommandInput\n * @param startKey - Optional start key for pagination\n */\n\n private async sendCommandDeep<T>(\n queryInput: QueryCommandInput | ScanCommandInput,\n startKey?: string | Record<string, any>,\n ): Promise<List<T>> {\n const result: List<T> = { items: [] };\n\n const size: number = (queryInput as any)?.Limit ?? 10;\n\n let lastEvaluatedKey: Record<string, AttributeValue>;\n\n if (startKey) {\n lastEvaluatedKey =\n typeof startKey === \"string\"\n ? parseLastEvaluatedKey<Record<string, AttributeValue>>(startKey) // will throw if invalid\n : startKey;\n }\n\n do {\n const response: QueryCommandOutput = await this.sendCommand({\n ...queryInput,\n ExclusiveStartKey: lastEvaluatedKey,\n });\n\n // no more items to fetch\n if (response.LastEvaluatedKey == undefined) {\n result?.items.push(...unMarshall<T>(response.Items));\n result.lastKey = undefined;\n return result;\n }\n\n if (response?.Items.length === 0 && response.LastEvaluatedKey) {\n lastEvaluatedKey = response.LastEvaluatedKey;\n continue;\n }\n\n if (result?.items.length + response?.Items.length <= size) {\n result?.items.push(...unMarshall<T>(response.Items));\n lastEvaluatedKey = response.LastEvaluatedKey;\n if (result?.items.length === size) {\n result.lastKey = toBase64(JSON.stringify(response.LastEvaluatedKey));\n return result;\n }\n continue;\n }\n\n const elementIndex = size - result?.items.length - 1;\n result?.items.push(...unMarshall<T>(response.Items.slice(0, elementIndex)));\n\n const index = this._indexMap.get(queryInput.IndexName);\n result.lastKey = generateLastEvaluatedKey(response.Items[elementIndex], index?.field, index?.sortKeyField);\n break;\n } while (lastEvaluatedKey);\n\n return result;\n }\n\n /**\n * Executes a single Query/Scan and returns the result as-is.\n * Supports pagination via ExclusiveStartKey.\n */\n private async sendCommand(\n commandInput: QueryCommandInput | ScanCommandInput,\n ): Promise<ScanCommandOutput | QueryCommandOutput> {\n commandInput.TableName = this._tableName;\n\n // if (startKey) {\n // commandInput.ExclusiveStartKey = typeof startKey === \"string\" ? parseLastEvaluatedKey(startKey) : startKey;\n // }\n\n if (!commandInput.Limit) {\n commandInput.Limit = this.DYNAMO_QUERY_LIMIT;\n }\n\n const isQuery = \"KeyConditionExpression\" in commandInput;\n const command = isQuery ? new QueryCommand(commandInput) : new ScanCommand(commandInput);\n\n log.debug(\"Sending command:\", commandInput);\n\n if (!this.dynamoDb) throw new ErrorDynamoDB(this._tableName, commandInput, \"dynamoDB client not initialized\");\n\n try {\n return await this.dynamoDb.send(command);\n } catch (error) {\n throw new ErrorDynamoDB(this._tableName, commandInput, error);\n }\n }\n}\n"]}
|
|
@@ -26,7 +26,7 @@ export declare abstract class BaseServiceImpl<T extends BaseEntity, D extends Ba
|
|
|
26
26
|
getIndexES(): string;
|
|
27
27
|
getIndexMapDB(): DynamoIndexMap;
|
|
28
28
|
findAll(): Promise<T[]>;
|
|
29
|
-
findAllMatch(filter: Filter): Promise<T[]>;
|
|
29
|
+
findAllMatch(filter: Filter | string): Promise<T[]>;
|
|
30
30
|
findAllByIndex(indexName: string, indexValue: any): Promise<T[]>;
|
|
31
31
|
findByField(fieldName: string, fieldValue: any): Promise<List<T>>;
|
|
32
32
|
findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T>;
|
|
@@ -84,7 +84,7 @@ export interface BaseService<T extends BaseEntity, R = any> extends BaseSocketSe
|
|
|
84
84
|
findQuery(queryParams: string): Promise<List<Partial<T>>>;
|
|
85
85
|
searchQuery(queryParams: string): Promise<Partial<T>[]>;
|
|
86
86
|
findAll(): Promise<T[]>;
|
|
87
|
-
findAllMatch(filter: Filter): Promise<T[]>;
|
|
87
|
+
findAllMatch(filter: Filter | string): Promise<T[]>;
|
|
88
88
|
findAllByIndex(indexName: string, indexValue: any): Promise<T[]>;
|
|
89
89
|
findByField(fieldName: string, fieldValue: any): Promise<List<T>>;
|
|
90
90
|
findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.interface.js","sourceRoot":"","sources":["../../src/service/base.service.interface.ts"],"names":[],"mappings":"","sourcesContent":["import { ActionDynamoDB, BaseEntity, BaseSocketService, DynamoIndexMap, Filter, List } from \"../index\";\nimport { EntityConfig } from \"@chinggis/types\";\n\n/**\n * Defines a generic base service interface for working with entities in both\n * DynamoDB and OpenSearch.\n */\nexport interface BaseService<T extends BaseEntity, R = any> extends BaseSocketService<R> {\n setConfig(config: EntityConfig): void;\n\n getTableName(): string;\n /**\n * Creates a new entity for the given user.\n * @param ownerId - The ID of the user who owns the entity.\n * @param entity - The entity to be created.\n * @param createdByUserId - The created userId.\n * @returns The created entity.\n */\n save(entity: Partial<T>, ownerId: string, createdByUserId?: string): Promise<T>;\n\n /**\n * Creates multiple new entities for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entity - An array of entities to be created.\n * @param createdByUserId - The created userId.\n * @param isTransactional - Whether to perform the operation in a transaction.\n * @returns An array of created entities.\n */\n saveAll(\n entity: Partial<T>[],\n ownerId: string,\n createdByUserId?: string,\n isTransactional?: boolean,\n ): Promise<Partial<T>[]>;\n\n /**\n * Applies partial updates to an entity for the given user.\n * Only the specified fields will be updated.\n * @param requestUserId - The ID of the user who owns the entity. If not exist means admin\n * @param entity - The entity with updated fields.\n * @returns The updated entity.\n */\n update(entity: T, requestUserId?: string): Promise<T>;\n\n /**\n * Applies partial updates to multiple entities for the given user.\n * Only the specified fields will be updated for each entity.\n * @param requestUserId - The ID of the user who owns the entities. If not exist means admin\n * @param entity - An array of entities with updated fields.\n * @param fields - The list of field names to update in each entity.\n * @param isTransactional - Whether to perform the operation in a transaction.\n * @returns True if all entities were successfully updated.\n */\n updateAll(entity: T[], fields: string[], requestUserId?: string, isTransactional?: boolean): Promise<boolean>;\n\n /**\n * Deletes an entity by ID for the given user.\n * @param ownerId - The ID of the user who owns the entity.\n * @param entityId - The ID of the entity to delete.\n * @returns True if the entity was successfully deleted.\n */\n remove(entityId: string, ownerId?: string): Promise<boolean>;\n\n /**\n * Deletes multiple entities by their IDs for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entityIds - An array of entity IDs to delete.\n * @returns True if all entities were successfully deleted.\n */\n removeAll(entityIds: string[], ownerId?: string): Promise<boolean>;\n\n /**\n * Retrieves an entity by its ID for the given user.\n * @param ownerId - The ID of the user who owns the entity.\n * @param entityId - The ID of the entity to retrieve.\n * @returns The requested entity.\n */\n findById(entityId: string, ownerId?: string): Promise<T>;\n\n /**\n * Retrieves multiple entities by their IDs for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entityIds - An array of entity IDs to retrieve.\n * @returns An array of found entities.\n */\n findByIds(entityIds: string[], ownerId?: string): Promise<T[]>;\n\n /**\n * Retrieves a paginated and filtered list of entities from DynamoDB.\n *\n * @param filter - Filtering and sorting options.\n * @returns A promise resolving to a paginated list of entities.\n */\n find(filter: Filter): Promise<List<Partial<T>>>;\n\n /**\n * Scans the table with non-index filters. Expensive; avoid it for hot paths.\n */\n scan(filter: Filter): Promise<List<Partial<T>>>;\n\n findQuery(queryParams: string): Promise<List<Partial<T>>>;\n\n searchQuery(queryParams: string): Promise<Partial<T>[]>;\n\n findAll(): Promise<T[]>;\n\n findAllMatch(filter: Filter): Promise<T[]>;\n\n findAllByIndex(indexName: string, indexValue: any): Promise<T[]>;\n\n findByField(fieldName: string, fieldValue: any): Promise<List<T>>;\n\n findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T>;\n\n throwError(code: number, message: string, errorContent?: any): void;\n\n throwErrorHttp(error: { message: string; code: number }, message: string, errorContent?: any): void;\n\n throwErrorDatabase(tableName: string, command: any, errorContent?: any): void;\n\n throwErrorValidation(entityName: string, validation: Map<string, any>, errorContent?: any): void;\n\n // throwError(httpStatus: number, message: string): void;\n /**\n * Retrieves a filtered and sorted list of entities from OpenSearch.\n *\n * @param filter - Filtering and sorting options.\n * @returns A promise resolving to the list of matching entities.\n */\n search(filter: Filter): Promise<T[]>;\n\n searchFieldNotExist(fieldName: string, from: number, size: number): Promise<Partial<T>[]>;\n\n /**\n * Changes the owner of an entity.\n * @param ownerId - The new owner's ID.\n * @param entityId - The ID of the entity to transfer.\n * @returns The updated entity with the new owner.\n */\n changeOwner(entityId: string, ownerId: string): Promise<T>;\n\n setTable(tableName: string, dynamoIndexMap: DynamoIndexMap): boolean;\n\n setOpensearch(indexName: string, opensearchEndpoint: string): boolean;\n\n getIndexES(): string;\n\n getIndexMapDB(): DynamoIndexMap;\n\n incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n\n decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n\n processChanges(itemOld: T, itemNew: T, action: ActionDynamoDB, tableName: string): Promise<any>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.interface.js","sourceRoot":"","sources":["../../src/service/base.service.interface.ts"],"names":[],"mappings":"","sourcesContent":["import { ActionDynamoDB, BaseEntity, BaseSocketService, DynamoIndexMap, Filter, List } from \"../index\";\nimport { EntityConfig } from \"@chinggis/types\";\n\n/**\n * Defines a generic base service interface for working with entities in both\n * DynamoDB and OpenSearch.\n */\nexport interface BaseService<T extends BaseEntity, R = any> extends BaseSocketService<R> {\n setConfig(config: EntityConfig): void;\n\n getTableName(): string;\n /**\n * Creates a new entity for the given user.\n * @param ownerId - The ID of the user who owns the entity.\n * @param entity - The entity to be created.\n * @param createdByUserId - The created userId.\n * @returns The created entity.\n */\n save(entity: Partial<T>, ownerId: string, createdByUserId?: string): Promise<T>;\n\n /**\n * Creates multiple new entities for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entity - An array of entities to be created.\n * @param createdByUserId - The created userId.\n * @param isTransactional - Whether to perform the operation in a transaction.\n * @returns An array of created entities.\n */\n saveAll(\n entity: Partial<T>[],\n ownerId: string,\n createdByUserId?: string,\n isTransactional?: boolean,\n ): Promise<Partial<T>[]>;\n\n /**\n * Applies partial updates to an entity for the given user.\n * Only the specified fields will be updated.\n * @param requestUserId - The ID of the user who owns the entity. If not exist means admin\n * @param entity - The entity with updated fields.\n * @returns The updated entity.\n */\n update(entity: T, requestUserId?: string): Promise<T>;\n\n /**\n * Applies partial updates to multiple entities for the given user.\n * Only the specified fields will be updated for each entity.\n * @param requestUserId - The ID of the user who owns the entities. If not exist means admin\n * @param entity - An array of entities with updated fields.\n * @param fields - The list of field names to update in each entity.\n * @param isTransactional - Whether to perform the operation in a transaction.\n * @returns True if all entities were successfully updated.\n */\n updateAll(entity: T[], fields: string[], requestUserId?: string, isTransactional?: boolean): Promise<boolean>;\n\n /**\n * Deletes an entity by ID for the given user.\n * @param ownerId - The ID of the user who owns the entity.\n * @param entityId - The ID of the entity to delete.\n * @returns True if the entity was successfully deleted.\n */\n remove(entityId: string, ownerId?: string): Promise<boolean>;\n\n /**\n * Deletes multiple entities by their IDs for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entityIds - An array of entity IDs to delete.\n * @returns True if all entities were successfully deleted.\n */\n removeAll(entityIds: string[], ownerId?: string): Promise<boolean>;\n\n /**\n * Retrieves an entity by its ID for the given user.\n * @param ownerId - The ID of the user who owns the entity.\n * @param entityId - The ID of the entity to retrieve.\n * @returns The requested entity.\n */\n findById(entityId: string, ownerId?: string): Promise<T>;\n\n /**\n * Retrieves multiple entities by their IDs for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entityIds - An array of entity IDs to retrieve.\n * @returns An array of found entities.\n */\n findByIds(entityIds: string[], ownerId?: string): Promise<T[]>;\n\n /**\n * Retrieves a paginated and filtered list of entities from DynamoDB.\n *\n * @param filter - Filtering and sorting options.\n * @returns A promise resolving to a paginated list of entities.\n */\n find(filter: Filter): Promise<List<Partial<T>>>;\n\n /**\n * Scans the table with non-index filters. Expensive; avoid it for hot paths.\n */\n scan(filter: Filter): Promise<List<Partial<T>>>;\n\n findQuery(queryParams: string): Promise<List<Partial<T>>>;\n\n searchQuery(queryParams: string): Promise<Partial<T>[]>;\n\n findAll(): Promise<T[]>;\n\n findAllMatch(filter: Filter | string): Promise<T[]>;\n\n findAllByIndex(indexName: string, indexValue: any): Promise<T[]>;\n\n findByField(fieldName: string, fieldValue: any): Promise<List<T>>;\n\n findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T>;\n\n throwError(code: number, message: string, errorContent?: any): void;\n\n throwErrorHttp(error: { message: string; code: number }, message: string, errorContent?: any): void;\n\n throwErrorDatabase(tableName: string, command: any, errorContent?: any): void;\n\n throwErrorValidation(entityName: string, validation: Map<string, any>, errorContent?: any): void;\n\n // throwError(httpStatus: number, message: string): void;\n /**\n * Retrieves a filtered and sorted list of entities from OpenSearch.\n *\n * @param filter - Filtering and sorting options.\n * @returns A promise resolving to the list of matching entities.\n */\n search(filter: Filter): Promise<T[]>;\n\n searchFieldNotExist(fieldName: string, from: number, size: number): Promise<Partial<T>[]>;\n\n /**\n * Changes the owner of an entity.\n * @param ownerId - The new owner's ID.\n * @param entityId - The ID of the entity to transfer.\n * @returns The updated entity with the new owner.\n */\n changeOwner(entityId: string, ownerId: string): Promise<T>;\n\n setTable(tableName: string, dynamoIndexMap: DynamoIndexMap): boolean;\n\n setOpensearch(indexName: string, opensearchEndpoint: string): boolean;\n\n getIndexES(): string;\n\n getIndexMapDB(): DynamoIndexMap;\n\n incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n\n decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n\n processChanges(itemOld: T, itemNew: T, action: ActionDynamoDB, tableName: string): Promise<any>;\n}\n"]}
|
|
@@ -121,6 +121,8 @@ class BaseServiceImpl extends socket_service_1.BaseSocketServiceIml {
|
|
|
121
121
|
return result;
|
|
122
122
|
}
|
|
123
123
|
async findAllMatch(filter) {
|
|
124
|
+
if (typeof filter === "string")
|
|
125
|
+
filter = (0, index_1.parseIndexFilter)(filter);
|
|
124
126
|
this.checkIsIndexedField(filter);
|
|
125
127
|
return await this.fetchAll(filter);
|
|
126
128
|
}
|
|
@@ -261,6 +263,10 @@ class BaseServiceImpl extends socket_service_1.BaseSocketServiceIml {
|
|
|
261
263
|
const response = await this.repoDB.find(filter);
|
|
262
264
|
result.push(...response.items);
|
|
263
265
|
filter.lastKey = response.lastKey;
|
|
266
|
+
if (result.length >= 5000) {
|
|
267
|
+
console.warn("too many items returned, breaking loop.");
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
264
270
|
} while (filter.lastKey);
|
|
265
271
|
return result;
|
|
266
272
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../src/service/base.service.ts"],"names":[],"mappings":";;;AAAA,oCAckB;AAClB,qDAAwD;AACxD,4CAAoF;AAIpF,MAAsB,eACpB,SAAQ,qCAAuB;IAGrB,MAAM,CAAI;IACV,MAAM,CAAI;IACV,MAAM,CAAe;IAE/B,YAAsB,MAAS,EAAE,MAAS;QACxC,KAAK,EAAE,CAAC;QACR,IAAI,MAAM,IAAI,IAAI,IAAI,CAAC,CAAC,MAAM,YAAY,sBAAc,CAAC;YACvD,OAAO,CAAC,KAAK,CAAC,6CAA6C,CAAC,CAAC;QAE/D,IAAI,MAAM,IAAI,IAAI,IAAI,CAAC,CAAC,MAAM,YAAY,sBAAc,CAAC;YACvD,OAAO,CAAC,KAAK,CAAC,6CAA6C,CAAC,CAAC;QAE/D,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI;YAAE,OAAO,CAAC,KAAK,CAAC,iCAAiC,CAAC,CAAC;QAEvF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;I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C,MAAc;QACnC,MAAM,MAAM,GAAiB,EAAE,CAAC;QAChC,GAAG,CAAC;YACF,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAChD,MAAM,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;YAC/B,MAAM,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;QACpC,CAAC,QAAQ,MAAM,CAAC,OAAO,EAAE;QAEzB,OAAO,MAAa,CAAC;IACvB,CAAC;CACF;AApVD,0CAoVC","sourcesContent":["import {\n ActionDynamoDB,\n addDates,\n addDatesAndId,\n BaseEntity,\n BaseRepoDB,\n BaseRepoDBImpl,\n BaseRepoES,\n BaseRepoESImpl,\n BaseService,\n DynamoIndexMap,\n Filter,\n List,\n parseIndexFilter,\n} from \"../index\";\nimport { BaseSocketServiceIml } from \"./socket.service\";\nimport { ErrorBase, ErrorDynamoDB, ErrorHttp, ErrorValidation } from \"../exception\";\n\nimport { EntityConfig } from \"@chinggis/types\";\n\nexport abstract class BaseServiceImpl<T extends BaseEntity, D extends BaseRepoDB<T>, S extends BaseRepoES<T>, R = any>\n extends BaseSocketServiceIml<R>\n implements BaseService<T, R>\n{\n protected repoDB: D;\n protected repoES: S;\n protected config: EntityConfig;\n\n protected constructor(repoDB: D, repoES: S) {\n super();\n if (repoDB != null && !(repoDB instanceof BaseRepoDBImpl))\n console.error(\"repoDB is not an instance of BaseRepoDBImpl\");\n\n if (repoES != null && !(repoES instanceof BaseRepoESImpl))\n console.error(\"repoES is not an instance of BaseRepoESImpl\");\n\n if (repoDB == null && repoES == null) console.error(\"repo initialization is required\");\n\n this.repoDB = repoDB;\n this.repoES = repoES;\n }\n\n getTableName(): string {\n return this.repoDB.getTableName();\n }\n\n abstract processChanges(itemOld: T, itemNew: T, action: ActionDynamoDB, tableName: string): Promise<any>;\n\n async findQuery(queryParams: string): Promise<List<Partial<T>>> {\n const filter = parseIndexFilter(queryParams, this.getIndexMapDB());\n this.checkIsIndexedField(filter);\n return await this.find(filter);\n }\n\n async searchQuery(queryParams: string): Promise<Partial<T>[]> {\n const filter = parseIndexFilter(queryParams);\n this.checkIsIndexedField(filter);\n return await this.search(filter);\n }\n\n async incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n return await this.repoDB.incrementValueByField(entityId, fieldName, value);\n }\n\n async decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n return await this.repoDB.decrementValueByField(entityId, fieldName, value);\n }\n\n async search(filter: Filter): Promise<T[]> {\n return (await this.repoES.find(filter)).items as T[];\n }\n\n async searchFieldNotExist(fieldName: string, from: number, size: number): Promise<Partial<T>[]> {\n return await this.repoES.fieldNotExists(fieldName, from, size);\n }\n\n async save(entity: Partial<T>, ownerId: string, createdByUserId?: string): Promise<T> {\n addDatesAndId(entity);\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n entity.createdBy = createdByUserId || ownerId;\n\n return await this.repoDB.save(entity);\n }\n\n async saveAll(\n entities: Partial<T>[],\n ownerId: string,\n createdByUserId?: string,\n isTransactional?: boolean,\n ): Promise<Partial<T>[]> {\n const entitiesUpdated = [];\n\n for (const item of entities) {\n const entity = addDatesAndId(item);\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n entity.createdBy = createdByUserId || ownerId;\n\n entitiesUpdated.push(entity);\n }\n\n return await this.repoDB.saveMany(entitiesUpdated, isTransactional);\n }\n\n async update(entity: T, requestUserId?: string): Promise<T> {\n if (requestUserId) {\n const item = await this.repoDB.findById(entity.id);\n if (item[this.config.OWNER_ID_FIELD_NAME] !== requestUserId)\n throw new ErrorHttp({ code: 403, error: \"PermissionDenied\" }, `No permission to resource: ${entity.id}`);\n entity.updatedBy = requestUserId;\n }\n entity = addDates(entity) as T;\n\n // if (!hasPermission(entity, userId, Permission.UPDATE)) throw new Error(\"Unauthorized access\");\n return await this.repoDB.update(entity);\n }\n\n async updateAll(\n entities: Partial<T>[],\n fields: string[],\n requestUserId?: string,\n isTransactional?: boolean,\n ): Promise<boolean> {\n if (requestUserId) log.warn(\"this methode is under development, cannot check ownership by updateAll\");\n\n return await this.repoDB.updateMany(entities, fields, isTransactional);\n }\n\n async remove(entityId: string, ownerId?: string): Promise<boolean> {\n const entity = await this.repoDB.findById(entityId);\n if (!entity) throw new Error(\"Entity not found\");\n\n if (ownerId && entity[this.config.OWNER_ID_FIELD_NAME] !== ownerId) return null;\n\n return await this.repoDB.delete(entityId);\n }\n\n async removeAll(entityIds: string[], ownerId?: string): Promise<boolean> {\n if (ownerId) log.warn(\"this methode is under development, cannot check ownership by removeAll\");\n return await this.repoDB.deleteMany(entityIds);\n }\n\n async changeOwner(entityId: string, ownerId: string): Promise<T> {\n const entity = await this.repoDB.findById(entityId);\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n return this.repoDB.update(entity);\n }\n\n setTable(tableName: string, dynamoIndexMap: DynamoIndexMap): boolean {\n this.repoDB.setTable(tableName);\n this.repoDB.setIndexMap(dynamoIndexMap);\n return true;\n }\n\n setOpensearch(indexName: string, opensearchEndpoint: string): boolean {\n this.repoES.setIndexName(indexName);\n this.repoES.setEndpoint(opensearchEndpoint);\n return true;\n }\n\n getIndexES(): string {\n return this.repoES.getIndexName();\n }\n\n getIndexMapDB(): DynamoIndexMap {\n return this.repoDB.getIndexMap();\n }\n\n async findAll(): Promise<T[]> {\n const result: T[] = [];\n\n const filter = parseIndexFilter(\"size=250\");\n\n do {\n const response = await this.repoDB.find(filter);\n result.push(...(response.items as T[]));\n filter.lastKey = response.lastKey;\n } while (filter.lastKey);\n\n return result;\n }\n\n async findAllMatch(filter: Filter): Promise<T[]> {\n this.checkIsIndexedField(filter);\n return await this.fetchAll(filter);\n }\n\n async findAllByIndex(indexName: string, indexValue: any): Promise<T[]> {\n // Create a filter object for validation\n const filter = { indexName: indexName, indexValue: indexValue };\n this.checkIsIndexedField(filter);\n\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return this.fetchAll(parsedFilter);\n }\n\n async findByField(fieldName: string, fieldValue: any): Promise<List<T>> {\n // Create a filter object for validation\n const filter = { [fieldName]: fieldValue, size: 100 };\n this.checkIsIndexedField(filter);\n const parsedFilter = parseIndexFilter(fieldName + \"=\" + fieldValue + \"&size=100\", this.getIndexMapDB());\n return (await this.find(parsedFilter)) as List<T>;\n }\n\n async findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T> {\n // Validate that the field name exists in the index map\n const filter = { [fieldName]: fieldValue };\n this.checkIsIndexedField(filter);\n\n const result = await this.findByField(fieldName, fieldValue);\n return result.items.length > 0 ? result.items[0] : null;\n }\n\n async find(filter: Filter): Promise<List<Partial<T>>> {\n // Validate that all field names in the filter exist in the index map\n this.checkIsIndexedField(filter);\n\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return await this.repoDB.find(parsedFilter);\n }\n\n async findById(entityId: string, profileId?: string): Promise<T> {\n const entity = await this.repoDB.findById(entityId);\n\n if (profileId && entity[this.config.OWNER_ID_FIELD_NAME] !== profileId) return null;\n\n return entity;\n }\n\n async findByIds(entityIds: string[], profileId?: string): Promise<T[]> {\n if (entityIds.length > 25) throw new ErrorDynamoDB(this.getTableName(), \"findByIds\", \"Too many entities\");\n\n const entities = await this.repoDB.findByIds(entityIds);\n if (!profileId) return entities;\n const ownEntities = [];\n for (const entity of entities) {\n if (entity[this.config.OWNER_ID_FIELD_NAME] !== profileId) continue;\n ownEntities.push(entity);\n }\n return ownEntities;\n }\n\n async scan(filter: Filter): Promise<List<Partial<T>>> {\n this.checkIsIndexedField(filter);\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return await this.repoDB.scan(parsedFilter);\n }\n\n throwErrorHttp(error: { message: string; code: number }, message?: string, errorContent?: any): void {\n throw new ErrorHttp({ code: error.code, error: error.message }, message, errorContent);\n }\n\n throwErrorDatabase(tableName: string, command: any, errorContent?: any): void {\n throw new ErrorDynamoDB(tableName, command, errorContent);\n }\n\n throwErrorValidation(entityName: string, validation: Map<string, any>, errorContent?: any): void {\n throw new ErrorValidation(entityName, validation, errorContent);\n }\n\n throwError(code: number, message: string, errorContent?: any): void {\n throw new ErrorBase(code, message, errorContent);\n }\n\n setConfig(config: EntityConfig) {\n this.config = config;\n\n this.setTable(config.DYNAMO_DB.NAME, config.DYNAMO_DB.MAP);\n\n if (this.repoDB) {\n this.repoDB.setIndexMap(config.DYNAMO_DB.MAP);\n this.repoDB.setTable(config.DYNAMO_DB.NAME);\n }\n\n if (this.repoES) {\n this.repoES.setEndpoint(config.OPEN_SEARCH.DOMAIN);\n this.repoES.setIndexName(config.OPEN_SEARCH.INDEX);\n }\n }\n\n /**\n * Validates that all field names in the filter exist in the index map.\n * Throws a Bad Request error if any field is not found in the available indexes.\n *\n * @param filter - The filter object containing field names to validate\n * @throws ErrorHttp with status 400 if validation fails\n */\n private checkIsIndexedField(filter: Filter): void {\n if (!filter || typeof filter !== \"object\") {\n return; // Skip validation for invalid filters\n }\n\n const indexMap = this.getIndexMapDB();\n if (!indexMap || indexMap.size === 0) {\n throw new ErrorHttp({ code: 400, error: \"Bad Request\" }, \"No indexes configured for this table\");\n }\n\n // Get all valid field names from all indexes\n const validFields = new Set<string>();\n\n // Add a partition key\n if (indexMap.partitionKey) {\n validFields.add(indexMap.partitionKey);\n }\n\n // Add fields from all indexes\n for (const [indexName, indexConfig] of indexMap.entries()) {\n if (indexConfig.field) {\n validFields.add(indexConfig.field);\n }\n if (indexConfig.rFields) {\n indexConfig.rFields.forEach((field) => validFields.add(field));\n }\n if (indexConfig.sortKeyField) {\n validFields.add(indexConfig.sortKeyField);\n }\n }\n\n // Check each field in the filter\n const invalidFields: string[] = [];\n for (const fieldName of Object.keys(filter)) {\n // Skip special filter properties that are not field names\n if (\n [\"indexName\", \"indexValue\", \"size\", \"lastKey\", \"fieldsInclude\", \"fieldsExclude\", \"rangeFilters\"].includes(\n fieldName,\n )\n ) {\n continue;\n }\n\n // Skip range filter fields (ageMin, ageMax, etc.)\n const rangeSuffixes = [\"Min\", \"Max\", \"From\", \"To\", \"Start\", \"End\"];\n const isRangeField = rangeSuffixes.some((suffix) => fieldName.endsWith(suffix));\n if (isRangeField) {\n continue;\n }\n\n if (!validFields.has(fieldName)) {\n invalidFields.push(fieldName);\n }\n }\n\n if (invalidFields.length > 0) {\n const availableFields = Array.from(validFields).sort();\n throw new ErrorHttp(\n { code: 400, error: \"Bad Request\" },\n `Invalid field names in filter: ${invalidFields.join(\", \")}. Available fields: ${availableFields.join(\", \")}`,\n );\n }\n }\n\n private async fetchAll(filter: Filter): Promise<T[]> {\n const result: Partial<T>[] = [];\n do {\n const response = await this.repoDB.find(filter);\n result.push(...response.items);\n filter.lastKey = response.lastKey;\n } while (filter.lastKey);\n\n return result as T[];\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../src/service/base.service.ts"],"names":[],"mappings":";;;AAAA,oCAckB;AAClB,qDAAwD;AACxD,4CAAoF;AAIpF,MAAsB,eACpB,SAAQ,qCAAuB;IAGrB,MAAM,CAAI;IACV,MAAM,CAAI;IACV,MAAM,CAAe;IAE/B,YAAsB,MAAS,EAAE,MAAS;QACxC,KAAK,EAAE,CAAC;QACR,IAAI,MAAM,IAAI,IAAI,IAAI,CAAC,CAAC,MAAM,YAAY,sBAAc,CAAC;YACvD,OAAO,CAAC,KAAK,CAAC,6CAA6C,CAAC,CAAC;QAE/D,IAAI,MAAM,IAAI,IAAI,IAAI,CAAC,CAAC,MAAM,YAAY,sBAAc,CAAC;YACvD,OAAO,CAAC,KAAK,CAAC,6CAA6C,CAAC,CAAC;QAE/D,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI;YAAE,OAAO,CAAC,KAAK,CAAC,iCAAiC,CAAC,CAAC;QAEvF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,Y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CAAC,IAAI,CAAC,EAAE,CAC9G,CAAC;QACJ,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,QAAQ,CAAC,MAAc;QACnC,MAAM,MAAM,GAAiB,EAAE,CAAC;QAChC,GAAG,CAAC;YACF,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAChD,MAAM,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;YAC/B,MAAM,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;YAClC,IAAI,MAAM,CAAC,MAAM,IAAI,IAAI,EAAE,CAAC;gBAC1B,OAAO,CAAC,IAAI,CAAC,yCAAyC,CAAC,CAAC;gBACxD,MAAM;YACR,CAAC;QACH,CAAC,QAAQ,MAAM,CAAC,OAAO,EAAE;QAEzB,OAAO,MAAa,CAAC;IACvB,CAAC;CACF;AAzVD,0CAyVC","sourcesContent":["import {\n ActionDynamoDB,\n addDates,\n addDatesAndId,\n BaseEntity,\n BaseRepoDB,\n BaseRepoDBImpl,\n BaseRepoES,\n BaseRepoESImpl,\n BaseService,\n DynamoIndexMap,\n Filter,\n List,\n parseIndexFilter,\n} from \"../index\";\nimport { BaseSocketServiceIml } from \"./socket.service\";\nimport { ErrorBase, ErrorDynamoDB, ErrorHttp, ErrorValidation } from \"../exception\";\n\nimport { EntityConfig } from \"@chinggis/types\";\n\nexport abstract class BaseServiceImpl<T extends BaseEntity, D extends BaseRepoDB<T>, S extends BaseRepoES<T>, R = any>\n extends BaseSocketServiceIml<R>\n implements BaseService<T, R>\n{\n protected repoDB: D;\n protected repoES: S;\n protected config: EntityConfig;\n\n protected constructor(repoDB: D, repoES: S) {\n super();\n if (repoDB != null && !(repoDB instanceof BaseRepoDBImpl))\n console.error(\"repoDB is not an instance of BaseRepoDBImpl\");\n\n if (repoES != null && !(repoES instanceof BaseRepoESImpl))\n console.error(\"repoES is not an instance of BaseRepoESImpl\");\n\n if (repoDB == null && repoES == null) console.error(\"repo initialization is required\");\n\n this.repoDB = repoDB;\n this.repoES = repoES;\n }\n\n getTableName(): string {\n return this.repoDB.getTableName();\n }\n\n abstract processChanges(itemOld: T, itemNew: T, action: ActionDynamoDB, tableName: string): Promise<any>;\n\n async findQuery(queryParams: string): Promise<List<Partial<T>>> {\n const filter = parseIndexFilter(queryParams, this.getIndexMapDB());\n this.checkIsIndexedField(filter);\n return await this.find(filter);\n }\n\n async searchQuery(queryParams: string): Promise<Partial<T>[]> {\n const filter = parseIndexFilter(queryParams);\n this.checkIsIndexedField(filter);\n return await this.search(filter);\n }\n\n async incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n return await this.repoDB.incrementValueByField(entityId, fieldName, value);\n }\n\n async decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n return await this.repoDB.decrementValueByField(entityId, fieldName, value);\n }\n\n async search(filter: Filter): Promise<T[]> {\n return (await this.repoES.find(filter)).items as T[];\n }\n\n async searchFieldNotExist(fieldName: string, from: number, size: number): Promise<Partial<T>[]> {\n return await this.repoES.fieldNotExists(fieldName, from, size);\n }\n\n async save(entity: Partial<T>, ownerId: string, createdByUserId?: string): Promise<T> {\n addDatesAndId(entity);\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n entity.createdBy = createdByUserId || ownerId;\n\n return await this.repoDB.save(entity);\n }\n\n async saveAll(\n entities: Partial<T>[],\n ownerId: string,\n createdByUserId?: string,\n isTransactional?: boolean,\n ): Promise<Partial<T>[]> {\n const entitiesUpdated = [];\n\n for (const item of entities) {\n const entity = addDatesAndId(item);\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n entity.createdBy = createdByUserId || ownerId;\n\n entitiesUpdated.push(entity);\n }\n\n return await this.repoDB.saveMany(entitiesUpdated, isTransactional);\n }\n\n async update(entity: T, requestUserId?: string): Promise<T> {\n if (requestUserId) {\n const item = await this.repoDB.findById(entity.id);\n if (item[this.config.OWNER_ID_FIELD_NAME] !== requestUserId)\n throw new ErrorHttp({ code: 403, error: \"PermissionDenied\" }, `No permission to resource: ${entity.id}`);\n entity.updatedBy = requestUserId;\n }\n entity = addDates(entity) as T;\n\n // if (!hasPermission(entity, userId, Permission.UPDATE)) throw new Error(\"Unauthorized access\");\n return await this.repoDB.update(entity);\n }\n\n async updateAll(\n entities: Partial<T>[],\n fields: string[],\n requestUserId?: string,\n isTransactional?: boolean,\n ): Promise<boolean> {\n if (requestUserId) log.warn(\"this methode is under development, cannot check ownership by updateAll\");\n\n return await this.repoDB.updateMany(entities, fields, isTransactional);\n }\n\n async remove(entityId: string, ownerId?: string): Promise<boolean> {\n const entity = await this.repoDB.findById(entityId);\n if (!entity) throw new Error(\"Entity not found\");\n\n if (ownerId && entity[this.config.OWNER_ID_FIELD_NAME] !== ownerId) return null;\n\n return await this.repoDB.delete(entityId);\n }\n\n async removeAll(entityIds: string[], ownerId?: string): Promise<boolean> {\n if (ownerId) log.warn(\"this methode is under development, cannot check ownership by removeAll\");\n return await this.repoDB.deleteMany(entityIds);\n }\n\n async changeOwner(entityId: string, ownerId: string): Promise<T> {\n const entity = await this.repoDB.findById(entityId);\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n return this.repoDB.update(entity);\n }\n\n setTable(tableName: string, dynamoIndexMap: DynamoIndexMap): boolean {\n this.repoDB.setTable(tableName);\n this.repoDB.setIndexMap(dynamoIndexMap);\n return true;\n }\n\n setOpensearch(indexName: string, opensearchEndpoint: string): boolean {\n this.repoES.setIndexName(indexName);\n this.repoES.setEndpoint(opensearchEndpoint);\n return true;\n }\n\n getIndexES(): string {\n return this.repoES.getIndexName();\n }\n\n getIndexMapDB(): DynamoIndexMap {\n return this.repoDB.getIndexMap();\n }\n\n async findAll(): Promise<T[]> {\n const result: T[] = [];\n\n const filter = parseIndexFilter(\"size=250\");\n\n do {\n const response = await this.repoDB.find(filter);\n result.push(...(response.items as T[]));\n filter.lastKey = response.lastKey;\n } while (filter.lastKey);\n\n return result;\n }\n\n async findAllMatch(filter: Filter | string): Promise<T[]> {\n if (typeof filter === \"string\") filter = parseIndexFilter(filter);\n this.checkIsIndexedField(filter);\n return await this.fetchAll(filter);\n }\n\n async findAllByIndex(indexName: string, indexValue: any): Promise<T[]> {\n // Create a filter object for validation\n const filter = { indexName: indexName, indexValue: indexValue };\n this.checkIsIndexedField(filter);\n\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return this.fetchAll(parsedFilter);\n }\n\n async findByField(fieldName: string, fieldValue: any): Promise<List<T>> {\n // Create a filter object for validation\n const filter = { [fieldName]: fieldValue, size: 100 };\n this.checkIsIndexedField(filter);\n const parsedFilter = parseIndexFilter(fieldName + \"=\" + fieldValue + \"&size=100\", this.getIndexMapDB());\n return (await this.find(parsedFilter)) as List<T>;\n }\n\n async findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T> {\n // Validate that the field name exists in the index map\n const filter = { [fieldName]: fieldValue };\n this.checkIsIndexedField(filter);\n\n const result = await this.findByField(fieldName, fieldValue);\n return result.items.length > 0 ? result.items[0] : null;\n }\n\n async find(filter: Filter): Promise<List<Partial<T>>> {\n // Validate that all field names in the filter exist in the index map\n this.checkIsIndexedField(filter);\n\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return await this.repoDB.find(parsedFilter);\n }\n\n async findById(entityId: string, profileId?: string): Promise<T> {\n const entity = await this.repoDB.findById(entityId);\n\n if (profileId && entity[this.config.OWNER_ID_FIELD_NAME] !== profileId) return null;\n\n return entity;\n }\n\n async findByIds(entityIds: string[], profileId?: string): Promise<T[]> {\n if (entityIds.length > 25) throw new ErrorDynamoDB(this.getTableName(), \"findByIds\", \"Too many entities\");\n\n const entities = await this.repoDB.findByIds(entityIds);\n if (!profileId) return entities;\n const ownEntities = [];\n for (const entity of entities) {\n if (entity[this.config.OWNER_ID_FIELD_NAME] !== profileId) continue;\n ownEntities.push(entity);\n }\n return ownEntities;\n }\n\n async scan(filter: Filter): Promise<List<Partial<T>>> {\n this.checkIsIndexedField(filter);\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return await this.repoDB.scan(parsedFilter);\n }\n\n throwErrorHttp(error: { message: string; code: number }, message?: string, errorContent?: any): void {\n throw new ErrorHttp({ code: error.code, error: error.message }, message, errorContent);\n }\n\n throwErrorDatabase(tableName: string, command: any, errorContent?: any): void {\n throw new ErrorDynamoDB(tableName, command, errorContent);\n }\n\n throwErrorValidation(entityName: string, validation: Map<string, any>, errorContent?: any): void {\n throw new ErrorValidation(entityName, validation, errorContent);\n }\n\n throwError(code: number, message: string, errorContent?: any): void {\n throw new ErrorBase(code, message, errorContent);\n }\n\n setConfig(config: EntityConfig) {\n this.config = config;\n\n this.setTable(config.DYNAMO_DB.NAME, config.DYNAMO_DB.MAP);\n\n if (this.repoDB) {\n this.repoDB.setIndexMap(config.DYNAMO_DB.MAP);\n this.repoDB.setTable(config.DYNAMO_DB.NAME);\n }\n\n if (this.repoES) {\n this.repoES.setEndpoint(config.OPEN_SEARCH.DOMAIN);\n this.repoES.setIndexName(config.OPEN_SEARCH.INDEX);\n }\n }\n\n /**\n * Validates that all field names in the filter exist in the index map.\n * Throws a Bad Request error if any field is not found in the available indexes.\n *\n * @param filter - The filter object containing field names to validate\n * @throws ErrorHttp with status 400 if validation fails\n */\n private checkIsIndexedField(filter: Filter): void {\n if (!filter || typeof filter !== \"object\") {\n return; // Skip validation for invalid filters\n }\n\n const indexMap = this.getIndexMapDB();\n if (!indexMap || indexMap.size === 0) {\n throw new ErrorHttp({ code: 400, error: \"Bad Request\" }, \"No indexes configured for this table\");\n }\n\n // Get all valid field names from all indexes\n const validFields = new Set<string>();\n\n // Add a partition key\n if (indexMap.partitionKey) {\n validFields.add(indexMap.partitionKey);\n }\n\n // Add fields from all indexes\n for (const [indexName, indexConfig] of indexMap.entries()) {\n if (indexConfig.field) {\n validFields.add(indexConfig.field);\n }\n if (indexConfig.rFields) {\n indexConfig.rFields.forEach((field) => validFields.add(field));\n }\n if (indexConfig.sortKeyField) {\n validFields.add(indexConfig.sortKeyField);\n }\n }\n\n // Check each field in the filter\n const invalidFields: string[] = [];\n for (const fieldName of Object.keys(filter)) {\n // Skip special filter properties that are not field names\n if (\n [\"indexName\", \"indexValue\", \"size\", \"lastKey\", \"fieldsInclude\", \"fieldsExclude\", \"rangeFilters\"].includes(\n fieldName,\n )\n ) {\n continue;\n }\n\n // Skip range filter fields (ageMin, ageMax, etc.)\n const rangeSuffixes = [\"Min\", \"Max\", \"From\", \"To\", \"Start\", \"End\"];\n const isRangeField = rangeSuffixes.some((suffix) => fieldName.endsWith(suffix));\n if (isRangeField) {\n continue;\n }\n\n if (!validFields.has(fieldName)) {\n invalidFields.push(fieldName);\n }\n }\n\n if (invalidFields.length > 0) {\n const availableFields = Array.from(validFields).sort();\n throw new ErrorHttp(\n { code: 400, error: \"Bad Request\" },\n `Invalid field names in filter: ${invalidFields.join(\", \")}. Available fields: ${availableFields.join(\", \")}`,\n );\n }\n }\n\n private async fetchAll(filter: Filter): Promise<T[]> {\n const result: Partial<T>[] = [];\n do {\n const response = await this.repoDB.find(filter);\n result.push(...response.items);\n filter.lastKey = response.lastKey;\n if (result.length >= 5000) {\n console.warn(\"too many items returned, breaking loop.\");\n break;\n }\n } while (filter.lastKey);\n\n return result as T[];\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crud.service.js","sourceRoot":"","sources":["../../src/service/crud.service.ts"],"names":[],"mappings":";;;;;;AAAA,oCAckB;AAClB,4CAAoF;AAIpF,kDAA0B;AAE1B,MAAsB,eAAe;IAGzB,MAAM,CAAI;IACV,MAAM,CAAI;IACV,MAAM,CAAe;IAE/B,YAAsB,MAAS,EAAE,MAAS;QACxC,IAAI,MAAM,IAAI,IAAI,IAAI,CAAC,CAAC,MAAM,YAAY,sBAAc,CAAC;YACvD,OAAO,CAAC,KAAK,CAAC,6CAA6C,CAAC,CAAC;QAE/D,IAAI,MAAM,IAAI,IAAI,I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{\n Action,\n BaseEntity,\n BaseRepoDB,\n BaseRepoDBImpl,\n BaseRepoES,\n BaseRepoESImpl,\n ChangeHistory,\n CognitoUser,\n computeChangedFields,\n DynamoIndexMap,\n Filter,\n List,\n parseIndexFilter,\n} from \"../index\";\nimport { ErrorBase, ErrorDynamoDB, ErrorHttp, ErrorValidation } from \"../exception\";\n\nimport { EntityConfig } from \"@chinggis/types\";\nimport { CrudService } from \"./crud.service.interface\";\nimport dayjs from \"dayjs\";\n\nexport abstract class CrudServiceImpl<T extends BaseEntity, D extends BaseRepoDB<T>, S extends BaseRepoES<T>>\n implements CrudService<T>\n{\n protected repoDB: D;\n protected repoES: S;\n protected config: EntityConfig;\n\n protected constructor(repoDB: D, repoES: S) {\n if (repoDB != null && !(repoDB instanceof BaseRepoDBImpl))\n console.error(\"repoDB is not an instance of BaseRepoDBImpl\");\n\n if (repoES != null && !(repoES instanceof BaseRepoESImpl))\n console.error(\"repoES is not an instance of BaseRepoESImpl\");\n\n if (repoDB == null && repoES == null) console.error(\"repo initialization is required\");\n\n this.repoDB = repoDB;\n this.repoES = repoES;\n }\n\n getTableName(): string {\n return this.repoDB.getTableName();\n }\n\n async findQuery(queryParams: string): Promise<List<Partial<T>>> {\n const filter = parseIndexFilter(queryParams, this.getIndexMapDB());\n this.checkIsIndexedField(filter);\n return await this.find(filter);\n }\n\n async searchQuery(queryParams: string): Promise<Partial<T>[]> {\n let filter = parseIndexFilter(queryParams);\n filter = this.parseOwnerFields(filter, this.config);\n this.checkIsIndexedField(filter);\n\n filter = this.setIndexField(filter, this.config);\n\n return await this.search(filter);\n }\n\n async incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n return await this.repoDB.incrementValueByField(entityId, fieldName, value);\n }\n\n async decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n return await this.repoDB.decrementValueByField(entityId, fieldName, value);\n }\n\n async search(filter: Filter): Promise<T[]> {\n let parsedFilter = this.parseOwnerFields(filter, this.config);\n parsedFilter = this.setIndexField(parsedFilter, this.config);\n\n return (await this.repoES.find(parsedFilter)).items as T[];\n }\n\n async searchFieldNotExist(fieldName: string, from: number, size: number): Promise<Partial<T>[]> {\n return await this.repoES.fieldNotExists(fieldName, from, size);\n }\n\n async save(entity: Partial<T>, ownerId: string, parentId?: string, createdByUser?: string | CognitoUser): Promise<T> {\n entity = this.setSystemData(entity, Action.CREATE, createdByUser);\n\n if (ownerId) {\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n entity.createdBy = createdByUser || ownerId;\n }\n if (parentId) entity[this.config.OWNER_PARENT_ID_FIELD_NAME] = parentId;\n\n return await this.repoDB.save(entity);\n }\n\n async saveAll(\n entities: Partial<T>[],\n ownerId: string,\n parentId?: string,\n createdByUser?: string | CognitoUser,\n isTransactional?: boolean,\n ): Promise<Partial<T>[]> {\n const entitiesUpdated = [];\n\n for (const item of entities) {\n // const entity = addDatesAndId(item);\n const entity = this.setSystemData(item, Action.CREATE, createdByUser || ownerId);\n\n if (parentId) entity[this.config.OWNER_PARENT_ID_FIELD_NAME] = parentId;\n\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n\n entitiesUpdated.push(entity);\n }\n\n return await this.repoDB.saveMany(entitiesUpdated, isTransactional);\n }\n\n async update(entity: T, requestUser?: CognitoUser): Promise<T> {\n const fieldName = this.config.DYNAMO_DB?.MAP?.partitionKey ?? \"id\";\n if (!entity || !entity[fieldName]) throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, `id required`);\n\n const item = await this.repoDB.findById(entity[fieldName]);\n\n if (!entity || !item) throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, `id not found`);\n\n if (\n requestUser &&\n !requestUser.isAdmin &&\n (item[this.config.OWNER_ID_FIELD_NAME] !== requestUser.profile ||\n item[this.config.OWNER_PARENT_ID_FIELD_NAME] !== requestUser.parentId)\n )\n throw new ErrorHttp({ code: 403, error: \"PermissionDenied\" }, `No permission to resource: ${entity.id}`);\n\n entity = this.setSystemData(entity, Action.UPDATE, requestUser, item);\n\n // if (!hasPermission(entity, userId, Permission.UPDATE)) throw new Error(\"Unauthorized access\");\n return await this.repoDB.update(entity);\n }\n\n async updateAll(\n entities: Partial<T>[],\n fields: string[],\n requestUser?: CognitoUser,\n isTransactional?: boolean,\n ): Promise<boolean> {\n if (requestUser) log.warn(\"this methode is under development, cannot check ownership by updateAll\");\n\n return await this.repoDB.updateMany(entities, fields, isTransactional);\n }\n\n async remove(entityId: string, requestUser: CognitoUser): Promise<boolean> {\n if (!entityId) throw new Error(\"Entity id required\");\n\n if (requestUser.isAdmin) return await this.repoDB.delete(entityId);\n\n const entity = await this.repoDB.findById(entityId);\n if (!entity) throw new Error(\"Entity not found\");\n\n if (\n entity[this.config.OWNER_ID_FIELD_NAME] !== requestUser.profile ||\n entity[this.config.OWNER_PARENT_ID_FIELD_NAME] !== requestUser.parentId\n )\n throw new ErrorHttp({ code: 403, error: \"PermissionDenied\" }, `No permission to resource: ${entity.id}`);\n\n return await this.repoDB.delete(entityId);\n }\n\n async removeAll(entityIds: string[], requestUser: CognitoUser): Promise<boolean> {\n if (requestUser) log.warn(\"this methode is under development, cannot check ownership by removeAll\");\n return await this.repoDB.deleteMany(entityIds);\n }\n\n async changeOwner(entityId: string, ownerId: string): Promise<T> {\n const entity = await this.repoDB.findById(entityId);\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n return this.repoDB.update(entity);\n }\n\n setTable(tableName: string, dynamoIndexMap: DynamoIndexMap): boolean {\n this.repoDB.setTable(tableName);\n this.repoDB.setIndexMap(dynamoIndexMap);\n return true;\n }\n\n setOpensearch(indexName: string, opensearchEndpoint: string): boolean {\n this.repoES.setIndexName(indexName);\n this.repoES.setEndpoint(opensearchEndpoint);\n return true;\n }\n\n getIndexES(): string {\n return this.repoES.getIndexName();\n }\n\n getIndexMapDB(): DynamoIndexMap {\n return this.repoDB.getIndexMap();\n }\n\n setIndexMapDB(indexMap: DynamoIndexMap): boolean {\n this.repoDB.setIndexMap(indexMap);\n return true;\n }\n\n async findAll(): Promise<T[]> {\n const result: T[] = [];\n\n const filter = parseIndexFilter(\"size=250\");\n\n do {\n const response = await this.repoDB.find(filter);\n result.push(...(response.items as T[]));\n filter.lastKey = response.lastKey;\n } while (filter.lastKey);\n\n return result;\n }\n\n async findAllMatch(filter: Filter): Promise<T[]> {\n this.checkIsIndexedField(filter);\n return await this.fetchAll(filter);\n }\n\n async findAllByIndex(indexName: string, indexValue: any): Promise<T[]> {\n // Create a filter object for validation\n const filter = { indexName: indexName, indexValue: indexValue };\n this.checkIsIndexedField(filter);\n\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return this.fetchAll(parsedFilter);\n }\n\n async findByField(fieldName: string, fieldValue: any): Promise<List<T>> {\n // Create a filter object for validation\n const filter = { [fieldName]: fieldValue, size: 100 };\n this.checkIsIndexedField(filter);\n const parsedFilter = parseIndexFilter(fieldName + \"=\" + fieldValue + \"&size=100\", this.getIndexMapDB());\n return (await this.find(parsedFilter)) as List<T>;\n }\n\n async findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T> {\n // Validate that the field name exists in the index map\n const filter = { [fieldName]: fieldValue };\n this.checkIsIndexedField(filter);\n\n const result = await this.findByField(fieldName, fieldValue);\n return result.items.length > 0 ? result.items[0] : null;\n }\n\n async find(filter: Filter): Promise<List<Partial<T>>> {\n // Validate that all field names in the filter exist in the index map\n let parsedFilter = this.parseOwnerFields(filter, this.config);\n\n this.checkIsIndexedField(parsedFilter);\n\n parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return await this.repoDB.find(parsedFilter);\n }\n\n async findById(entityId: string, requestUser?: CognitoUser): Promise<T> {\n const entity = await this.repoDB.findById(entityId);\n\n if (!entity) return null;\n\n if (!requestUser || requestUser.isAdmin) return entity;\n\n const isOwnerParent = entity[this.config.OWNER_PARENT_ID_FIELD_NAME] == requestUser.profile;\n const isParent = entity[this.config.OWNER_ID_FIELD_NAME] == requestUser.profile;\n\n if (!requestUser.profile || isOwnerParent || isParent) {\n return entity;\n }\n\n return null;\n }\n\n async findByIds(entityIds: string[], requestUser?: CognitoUser): Promise<T[]> {\n if (entityIds.length > 25) throw new ErrorDynamoDB(this.getTableName(), \"findByIds\", \"Too many entities\");\n\n const entities = await this.repoDB.findByIds(entityIds);\n\n if (!requestUser || requestUser.isAdmin) return entities;\n\n const ownEntities = [];\n for (const entity of entities) {\n if (\n entity[this.config.OWNER_PARENT_ID_FIELD_NAME] == requestUser.profile ||\n entity[this.config.OWNER_ID_FIELD_NAME] == requestUser.profile\n ) {\n ownEntities.push(entity);\n }\n }\n return ownEntities;\n }\n\n async scan(filter: Filter): Promise<List<Partial<T>>> {\n this.checkIsIndexedField(filter);\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return await this.repoDB.scan(parsedFilter);\n }\n\n throwErrorHttp(error: { message: string; code: number }, message?: string, errorContent?: any): void {\n throw new ErrorHttp({ code: error.code, error: error.message }, message, errorContent);\n }\n\n throwErrorDatabase(tableName: string, command: any, errorContent?: any): void {\n throw new ErrorDynamoDB(tableName, command, errorContent);\n }\n\n throwErrorValidation(entityName: string, validation: Map<string, any>, errorContent?: any): void {\n throw new ErrorValidation(entityName, validation, errorContent);\n }\n\n throwError(code: number, message: string, errorContent?: any): void {\n throw new ErrorBase(code, message, errorContent);\n }\n\n setConfig(config: EntityConfig) {\n this.config = config;\n\n if (this.repoDB) {\n this.repoDB.setIndexMap(config.DYNAMO_DB?.MAP);\n this.repoDB.setTable(config.DYNAMO_DB?.NAME);\n }\n\n if (this.repoES) {\n this.repoES.setEndpoint(config.OPEN_SEARCH.DOMAIN);\n this.repoES.setIndexName(config.OPEN_SEARCH.INDEX);\n }\n }\n\n /**\n * Validates that all field names in the filter exist in the index map.\n * Throws a Bad Request error if any field is not found in the available indexes.\n *\n * @param filter - The filter object containing field names to validate\n * @throws ErrorHttp with status 400 if validation fails\n */\n private checkIsIndexedField(filter: Filter): void {\n if (!filter || typeof filter !== \"object\") {\n return; // Skip validation for invalid filters\n }\n\n const indexMap = this.getIndexMapDB();\n if (!indexMap || indexMap.size === 0) {\n throw new ErrorHttp({ code: 400, error: \"Bad Request\" }, \"No indexes configured for this table\");\n }\n\n // Get all valid field names from all indexes\n const validFields = new Set<string>();\n\n // Add a partition key\n if (indexMap.partitionKey) {\n validFields.add(indexMap.partitionKey);\n }\n\n // Add fields from all indexes\n for (const [indexName, indexConfig] of indexMap.entries()) {\n if (indexConfig.field) {\n validFields.add(indexConfig.field);\n }\n if (indexConfig.rFields) {\n indexConfig.rFields.forEach((field) => validFields.add(field));\n }\n if (indexConfig.sortKeyField) {\n validFields.add(indexConfig.sortKeyField);\n }\n }\n\n // Check each field in the filter\n const invalidFields: string[] = [];\n for (const fieldName of Object.keys(filter)) {\n // Skip special filter properties that are not field names\n if (\n [\"indexName\", \"indexValue\", \"size\", \"lastKey\", \"fieldsInclude\", \"fieldsExclude\", \"rangeFilters\"].includes(\n fieldName,\n )\n ) {\n continue;\n }\n\n // Skip range filter fields (ageMin, ageMax, etc.)\n const rangeSuffixes = [\"Min\", \"Max\", \"From\", \"To\", \"Start\", \"End\"];\n const isRangeField = rangeSuffixes.some((suffix) => fieldName.endsWith(suffix));\n if (isRangeField) {\n continue;\n }\n\n if (!validFields.has(fieldName)) {\n invalidFields.push(fieldName);\n }\n }\n\n if (invalidFields.length > 0) {\n const availableFields = Array.from(validFields).sort();\n throw new ErrorHttp(\n { code: 400, error: \"Bad Request\" },\n `Invalid field names in filter: ${invalidFields.join(\", \")}. Available fields: ${availableFields.join(\", \")}`,\n );\n }\n }\n\n private async fetchAll(filter: Filter): Promise<T[]> {\n const result: Partial<T>[] = [];\n do {\n const response = await this.repoDB.find(filter);\n result.push(...response.items);\n filter.lastKey = response.lastKey;\n } while (filter.lastKey);\n\n return result as T[];\n }\n\n private parseOwnerFields(filter: Filter, entityConfig: EntityConfig) {\n const parsedFilter = filter;\n\n log.debug(\"input filter\", parsedFilter);\n\n if (parsedFilter.ownerParentId && !entityConfig.OWNER_PARENT_ID_FIELD_NAME) {\n parsedFilter.profileId = parsedFilter.ownerParentId;\n delete parsedFilter.ownerParentId;\n }\n if (!parsedFilter.profileId) delete parsedFilter.profileId;\n\n if (parsedFilter.ownerParentId && entityConfig.OWNER_PARENT_ID_FIELD_NAME) {\n parsedFilter[entityConfig.OWNER_PARENT_ID_FIELD_NAME] = parsedFilter.ownerParentId;\n if (entityConfig.OWNER_PARENT_ID_FIELD_NAME !== parsedFilter.ownerParentId) delete parsedFilter.ownerParentId;\n }\n\n if (parsedFilter.profileId && entityConfig.OWNER_ID_FIELD_NAME) {\n parsedFilter[entityConfig.OWNER_ID_FIELD_NAME] = parsedFilter.profileId;\n if (entityConfig.OWNER_ID_FIELD_NAME !== parsedFilter.owderId) delete parsedFilter.profileId;\n }\n\n // if (parsedFilter.ownerId && entityConfig.OWNER_ID_FIELD_NAME) {\n // parsedFilter[entityConfig.OWNER_ID_FIELD_NAME] = parsedFilter.ownerId;\n // if (entityConfig.OWNER_ID_FIELD_NAME !== parsedFilter.ownerId) delete parsedFilter.ownerId;\n // }\n log.debug(\"parsedFilter\", parsedFilter);\n\n return parsedFilter;\n }\n private setSystemData(itemNew: Partial<T>, action: Action, requestUser?: string | CognitoUser, itemOld?: T): T {\n if (!action || action === Action.DELETE || action === Action.READ) return itemNew as T;\n\n const date = dayjs().toISOString();\n const user = this.extractUser(requestUser);\n\n switch (action) {\n case Action.CREATE:\n return this.handleCreate(itemNew, user, date);\n case Action.UPDATE:\n return this.handleUpdate(itemNew, itemOld, user, date);\n default:\n return itemNew as T;\n }\n }\n\n private extractUser(requestUser?: string | CognitoUser): string {\n if (!requestUser) return \"system\";\n return typeof requestUser === \"string\" ? requestUser : requestUser.username;\n }\n\n private handleCreate(itemNew: Partial<T>, user: string, date: string): T {\n const dayjsData = dayjs(new Date(date));\n itemNew[this.config.DYNAMO_DB.MAP.partitionKey ?? \"id\"] = crypto.randomUUID();\n itemNew.createdAt = date;\n itemNew.createdBy = user;\n itemNew.year = dayjsData.year().toString();\n itemNew.yearMonth = dayjsData.year() + \"-\" + (dayjsData.month() + 1);\n\n if (!this.config.TRACE_CHANGE?.fields) return itemNew as T;\n\n itemNew.history = this.addHistory(itemNew.history, { action: Action.CREATE, user, date });\n return itemNew as T;\n }\n\n private handleUpdate(itemNew: Partial<T>, itemOld: T | undefined, user: string, date: string): T {\n itemNew.createdBy = itemNew.createdBy || itemOld?.createdBy;\n itemNew.updatedBy = itemNew.updatedBy || { username: user };\n itemNew.history = itemNew.history || itemOld?.history;\n\n if (!this.config.TRACE_CHANGE?.fields || !itemOld) return itemNew as T;\n\n delete itemNew.updatedBy;\n\n const changes = computeChangedFields(itemOld, itemNew, this.config.TRACE_CHANGE);\n if (changes.length > 0) {\n itemNew.history = this.addHistory(itemNew.history, {\n action: Action.UPDATE,\n user,\n date,\n changes,\n });\n }\n\n return itemNew as T;\n }\n\n private addHistory(history: ChangeHistory[] | undefined, entry: ChangeHistory): ChangeHistory[] {\n // skip empty or invalid history entries\n if (!entry.changes || entry.changes.length === 0) {\n return history || [];\n }\n\n // clone to avoid accidental mutation\n const newHistory = [...(history || [])];\n\n // optional: limit max history size (e.g., last 100 changes)\n const MAX_HISTORY_ENTRIES = 100;\n if (newHistory.length >= MAX_HISTORY_ENTRIES) {\n newHistory.shift(); // remove oldest\n }\n\n newHistory.push(entry);\n return newHistory;\n }\n\n private setIndexField(filter: Filter, config: EntityConfig) {\n if (!filter.indexName || !filter.indexValue) return filter;\n\n const indexMap = config.DYNAMO_DB.MAP;\n if (!indexMap || indexMap.size === 0) return filter;\n\n const indexConfig = indexMap.get(filter.indexName);\n if (!indexConfig) return filter;\n\n filter.indexName = indexConfig.field;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"crud.service.js","sourceRoot":"","sources":["../../src/service/crud.service.ts"],"names":[],"mappings":";;;;;;AAAA,oCAekB;AAClB,4CAAoF;AAIpF,kDAA0B;AAE1B,MAAsB,eAAe;IAGzB,MAAM,CAA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,CAAC;QACtC,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,IAAI,KAAK,CAAC;YAAE,OAAO,MAAM,CAAC;QAEpD,MAAM,WAAW,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,CAAC,WAAW;YAAE,OAAO,MAAM,CAAC;QAEhC,MAAM,CAAC,SAAS,GAAG,WAAW,CAAC,KAAK,CAAC;IACvC,CAAC;CACF;AA3fD,0CA2fC","sourcesContent":["import {\n Action,\n BaseEntity,\n BaseRepoDB,\n BaseRepoDBImpl,\n BaseRepoES,\n BaseRepoESImpl,\n ChangeHistory,\n CognitoUser,\n computeChangedFields,\n DynamoIndexMap,\n Filter,\n List,\n parseFilter,\n parseIndexFilter,\n} from \"../index\";\nimport { ErrorBase, ErrorDynamoDB, ErrorHttp, ErrorValidation } from \"../exception\";\n\nimport { EntityConfig } from \"@chinggis/types\";\nimport { CrudService } from \"./crud.service.interface\";\nimport dayjs from \"dayjs\";\n\nexport abstract class CrudServiceImpl<T extends BaseEntity, D extends BaseRepoDB<T>, S extends BaseRepoES<T>>\n implements CrudService<T>\n{\n protected repoDB: D;\n protected repoES: S;\n protected config: EntityConfig;\n\n protected constructor(repoDB: D, repoES: S) {\n if (repoDB != null && !(repoDB instanceof BaseRepoDBImpl))\n console.error(\"repoDB is not an instance of BaseRepoDBImpl\");\n\n if (repoES != null && !(repoES instanceof BaseRepoESImpl))\n console.error(\"repoES is not an instance of BaseRepoESImpl\");\n\n if (repoDB == null && repoES == null) console.error(\"repo initialization is required\");\n\n this.repoDB = repoDB;\n this.repoES = repoES;\n }\n\n getTableName(): string {\n return this.repoDB.getTableName();\n }\n\n async findQuery(queryParams: string): Promise<List<Partial<T>>> {\n const filter = parseIndexFilter(queryParams, this.getIndexMapDB());\n this.checkIsIndexedField(filter);\n return await this.find(filter);\n }\n\n async searchQuery(queryParams: string): Promise<Partial<T>[]> {\n let filter = parseIndexFilter(queryParams);\n filter = this.parseOwnerFields(filter, this.config);\n this.checkIsIndexedField(filter);\n\n filter = this.setIndexField(filter, this.config);\n\n return await this.search(filter);\n }\n\n async incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n return await this.repoDB.incrementValueByField(entityId, fieldName, value);\n }\n\n async decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T> {\n return await this.repoDB.decrementValueByField(entityId, fieldName, value);\n }\n\n async search(filter: Filter): Promise<T[]> {\n let parsedFilter = this.parseOwnerFields(filter, this.config);\n parsedFilter = this.setIndexField(parsedFilter, this.config);\n\n return (await this.repoES.find(parsedFilter)).items as T[];\n }\n\n async searchFieldNotExist(fieldName: string, from: number, size: number): Promise<Partial<T>[]> {\n return await this.repoES.fieldNotExists(fieldName, from, size);\n }\n\n async save(entity: Partial<T>, ownerId: string, parentId?: string, createdByUser?: string | CognitoUser): Promise<T> {\n entity = this.setSystemData(entity, Action.CREATE, createdByUser);\n\n if (ownerId) {\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n entity.createdBy = createdByUser || ownerId;\n }\n if (parentId) entity[this.config.OWNER_PARENT_ID_FIELD_NAME] = parentId;\n\n return await this.repoDB.save(entity);\n }\n\n async saveAll(\n entities: Partial<T>[],\n ownerId: string,\n parentId?: string,\n createdByUser?: string | CognitoUser,\n isTransactional?: boolean,\n ): Promise<Partial<T>[]> {\n const entitiesUpdated = [];\n\n for (const item of entities) {\n // const entity = addDatesAndId(item);\n const entity = this.setSystemData(item, Action.CREATE, createdByUser || ownerId);\n\n if (parentId) entity[this.config.OWNER_PARENT_ID_FIELD_NAME] = parentId;\n\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n\n entitiesUpdated.push(entity);\n }\n\n return await this.repoDB.saveMany(entitiesUpdated, isTransactional);\n }\n\n async update(entity: T, requestUser?: CognitoUser): Promise<T> {\n const fieldName = this.config.DYNAMO_DB?.MAP?.partitionKey ?? \"id\";\n if (!entity || !entity[fieldName]) throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, `id required`);\n\n const item = await this.repoDB.findById(entity[fieldName]);\n\n if (!entity || !item) throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, `id not found`);\n\n if (\n requestUser &&\n !requestUser.isAdmin &&\n (item[this.config.OWNER_ID_FIELD_NAME] !== requestUser.profile ||\n item[this.config.OWNER_PARENT_ID_FIELD_NAME] !== requestUser.parentId)\n )\n throw new ErrorHttp({ code: 403, error: \"PermissionDenied\" }, `No permission to resource: ${entity.id}`);\n\n entity = this.setSystemData(entity, Action.UPDATE, requestUser, item);\n\n // if (!hasPermission(entity, userId, Permission.UPDATE)) throw new Error(\"Unauthorized access\");\n return await this.repoDB.update(entity);\n }\n\n async updateAll(\n entities: Partial<T>[],\n fields: string[],\n requestUser?: CognitoUser,\n isTransactional?: boolean,\n ): Promise<boolean> {\n if (requestUser) log.warn(\"this methode is under development, cannot check ownership by updateAll\");\n\n return await this.repoDB.updateMany(entities, fields, isTransactional);\n }\n\n async remove(entityId: string, requestUser: CognitoUser): Promise<boolean> {\n if (!entityId) throw new Error(\"Entity id required\");\n\n if (requestUser.isAdmin) return await this.repoDB.delete(entityId);\n\n const entity = await this.repoDB.findById(entityId);\n if (!entity) throw new Error(\"Entity not found\");\n\n if (\n entity[this.config.OWNER_ID_FIELD_NAME] !== requestUser.profile ||\n entity[this.config.OWNER_PARENT_ID_FIELD_NAME] !== requestUser.parentId\n )\n throw new ErrorHttp({ code: 403, error: \"PermissionDenied\" }, `No permission to resource: ${entity.id}`);\n\n return await this.repoDB.delete(entityId);\n }\n\n async removeAll(entityIds: string[], requestUser: CognitoUser): Promise<boolean> {\n if (requestUser) log.warn(\"this methode is under development, cannot check ownership by removeAll\");\n return await this.repoDB.deleteMany(entityIds);\n }\n\n async changeOwner(entityId: string, ownerId: string): Promise<T> {\n const entity = await this.repoDB.findById(entityId);\n entity[this.config.OWNER_ID_FIELD_NAME] = ownerId;\n return this.repoDB.update(entity);\n }\n\n setTable(tableName: string, dynamoIndexMap: DynamoIndexMap): boolean {\n this.repoDB.setTable(tableName);\n this.repoDB.setIndexMap(dynamoIndexMap);\n return true;\n }\n\n setOpensearch(indexName: string, opensearchEndpoint: string): boolean {\n this.repoES.setIndexName(indexName);\n this.repoES.setEndpoint(opensearchEndpoint);\n return true;\n }\n\n getIndexES(): string {\n return this.repoES.getIndexName();\n }\n\n getIndexMapDB(): DynamoIndexMap {\n return this.repoDB.getIndexMap();\n }\n\n setIndexMapDB(indexMap: DynamoIndexMap): boolean {\n this.repoDB.setIndexMap(indexMap);\n return true;\n }\n\n async findAll(): Promise<T[]> {\n const result: T[] = [];\n\n const filter = parseIndexFilter(\"size=250\");\n\n do {\n const response = await this.repoDB.find(filter);\n result.push(...(response.items as T[]));\n filter.lastKey = response.lastKey;\n } while (filter.lastKey);\n\n return result;\n }\n\n async findAllMatch(filter: Filter): Promise<T[]> {\n this.checkIsIndexedField(filter);\n return await this.fetchAll(filter);\n }\n\n async findAllByIndex(indexName: string, indexValue: any): Promise<T[]> {\n // Create a filter object for validation\n const filter = { indexName: indexName, indexValue: indexValue };\n this.checkIsIndexedField(filter);\n\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return this.fetchAll(parsedFilter);\n }\n\n async findByField(fieldName: string, fieldValue: any): Promise<List<T>> {\n // Create a filter object for validation\n const filter = { [fieldName]: fieldValue, size: 100 };\n this.checkIsIndexedField(filter);\n const parsedFilter = parseIndexFilter(fieldName + \"=\" + fieldValue + \"&size=100\", this.getIndexMapDB());\n return (await this.find(parsedFilter)) as List<T>;\n }\n\n async findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T> {\n // Validate that the field name exists in the index map\n const filter = { [fieldName]: fieldValue };\n this.checkIsIndexedField(filter);\n\n const result = await this.findByField(fieldName, fieldValue);\n return result.items.length > 0 ? result.items[0] : null;\n }\n\n async find(filter: Filter): Promise<List<Partial<T>>> {\n // Validate that all field names in the filter exist in the index map\n let parsedFilter = this.parseOwnerFields(filter, this.config);\n\n this.checkIsIndexedField(parsedFilter);\n\n parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return await this.repoDB.find(parsedFilter);\n }\n\n async findById(entityId: string, requestUser?: CognitoUser): Promise<T> {\n const entity = await this.repoDB.findById(entityId);\n\n if (!entity) return null;\n\n if (!requestUser || requestUser.isAdmin) return entity;\n\n const isOwnerParent = entity[this.config.OWNER_PARENT_ID_FIELD_NAME] == requestUser.profile;\n const isParent = entity[this.config.OWNER_ID_FIELD_NAME] == requestUser.profile;\n\n if (!requestUser.profile || isOwnerParent || isParent) {\n return entity;\n }\n\n return null;\n }\n\n async findByIds(entityIds: string[], requestUser?: CognitoUser): Promise<T[]> {\n if (entityIds.length > 25) throw new ErrorDynamoDB(this.getTableName(), \"findByIds\", \"Too many entities\");\n\n const entities = await this.repoDB.findByIds(entityIds);\n\n if (!requestUser || requestUser.isAdmin) return entities;\n\n const ownEntities = [];\n for (const entity of entities) {\n if (\n entity[this.config.OWNER_PARENT_ID_FIELD_NAME] == requestUser.profile ||\n entity[this.config.OWNER_ID_FIELD_NAME] == requestUser.profile\n ) {\n ownEntities.push(entity);\n }\n }\n return ownEntities;\n }\n\n async scan(filter: Filter): Promise<List<Partial<T>>> {\n this.checkIsIndexedField(filter);\n const parsedFilter = parseIndexFilter(filter, this.getIndexMapDB());\n return await this.repoDB.scan(parsedFilter);\n }\n\n throwErrorHttp(error: { message: string; code: number }, message?: string, errorContent?: any): void {\n throw new ErrorHttp({ code: error.code, error: error.message }, message, errorContent);\n }\n\n throwErrorDatabase(tableName: string, command: any, errorContent?: any): void {\n throw new ErrorDynamoDB(tableName, command, errorContent);\n }\n\n throwErrorValidation(entityName: string, validation: Map<string, any>, errorContent?: any): void {\n throw new ErrorValidation(entityName, validation, errorContent);\n }\n\n throwError(code: number, message: string, errorContent?: any): void {\n throw new ErrorBase(code, message, errorContent);\n }\n\n setConfig(config: EntityConfig) {\n this.config = config;\n\n if (this.repoDB) {\n this.repoDB.setIndexMap(config.DYNAMO_DB?.MAP);\n this.repoDB.setTable(config.DYNAMO_DB?.NAME);\n }\n\n if (this.repoES) {\n this.repoES.setEndpoint(config.OPEN_SEARCH.DOMAIN);\n this.repoES.setIndexName(config.OPEN_SEARCH.INDEX);\n }\n }\n\n /**\n * Validates that all field names in the filter exist in the index map.\n * Throws a Bad Request error if any field is not found in the available indexes.\n *\n * @param filter - The filter object containing field names to validate\n * @throws ErrorHttp with status 400 if validation fails\n */\n private checkIsIndexedField(filter: Filter): void {\n if (!filter || typeof filter !== \"object\") {\n return; // Skip validation for invalid filters\n }\n\n const indexMap = this.getIndexMapDB();\n if (!indexMap || indexMap.size === 0) {\n throw new ErrorHttp({ code: 400, error: \"Bad Request\" }, \"No indexes configured for this table\");\n }\n\n // Get all valid field names from all indexes\n const validFields = new Set<string>();\n\n // Add a partition key\n if (indexMap.partitionKey) {\n validFields.add(indexMap.partitionKey);\n }\n\n // Add fields from all indexes\n for (const [indexName, indexConfig] of indexMap.entries()) {\n if (indexConfig.field) {\n validFields.add(indexConfig.field);\n }\n if (indexConfig.rFields) {\n indexConfig.rFields.forEach((field) => validFields.add(field));\n }\n if (indexConfig.sortKeyField) {\n validFields.add(indexConfig.sortKeyField);\n }\n }\n\n // Check each field in the filter\n const invalidFields: string[] = [];\n for (const fieldName of Object.keys(filter)) {\n // Skip special filter properties that are not field names\n if (\n [\"indexName\", \"indexValue\", \"size\", \"lastKey\", \"fieldsInclude\", \"fieldsExclude\", \"rangeFilters\"].includes(\n fieldName,\n )\n ) {\n continue;\n }\n\n // Skip range filter fields (ageMin, ageMax, etc.)\n const rangeSuffixes = [\"Min\", \"Max\", \"From\", \"To\", \"Start\", \"End\"];\n const isRangeField = rangeSuffixes.some((suffix) => fieldName.endsWith(suffix));\n if (isRangeField) {\n continue;\n }\n\n if (!validFields.has(fieldName)) {\n invalidFields.push(fieldName);\n }\n }\n\n if (invalidFields.length > 0) {\n const availableFields = Array.from(validFields).sort();\n throw new ErrorHttp(\n { code: 400, error: \"Bad Request\" },\n `Invalid field names in filter: ${invalidFields.join(\", \")}. Available fields: ${availableFields.join(\", \")}`,\n );\n }\n }\n\n private async fetchAll(filter: Filter | string): Promise<T[]> {\n if (typeof filter === \"string\") filter = parseFilter(filter);\n\n const result: Partial<T>[] = [];\n do {\n const response = await this.repoDB.find(filter);\n result.push(...response.items);\n filter.lastKey = response.lastKey;\n } while (filter.lastKey);\n\n return result as T[];\n }\n\n private parseOwnerFields(filter: Filter, entityConfig: EntityConfig) {\n const parsedFilter = filter;\n\n log.debug(\"input filter\", parsedFilter);\n\n if (parsedFilter.ownerParentId && !entityConfig.OWNER_PARENT_ID_FIELD_NAME) {\n parsedFilter.profileId = parsedFilter.ownerParentId;\n delete parsedFilter.ownerParentId;\n }\n if (!parsedFilter.profileId) delete parsedFilter.profileId;\n\n if (parsedFilter.ownerParentId && entityConfig.OWNER_PARENT_ID_FIELD_NAME) {\n parsedFilter[entityConfig.OWNER_PARENT_ID_FIELD_NAME] = parsedFilter.ownerParentId;\n if (entityConfig.OWNER_PARENT_ID_FIELD_NAME !== parsedFilter.ownerParentId) delete parsedFilter.ownerParentId;\n }\n\n if (parsedFilter.profileId && entityConfig.OWNER_ID_FIELD_NAME) {\n parsedFilter[entityConfig.OWNER_ID_FIELD_NAME] = parsedFilter.profileId;\n if (entityConfig.OWNER_ID_FIELD_NAME !== parsedFilter.owderId) delete parsedFilter.profileId;\n }\n\n // if (parsedFilter.ownerId && entityConfig.OWNER_ID_FIELD_NAME) {\n // parsedFilter[entityConfig.OWNER_ID_FIELD_NAME] = parsedFilter.ownerId;\n // if (entityConfig.OWNER_ID_FIELD_NAME !== parsedFilter.ownerId) delete parsedFilter.ownerId;\n // }\n log.debug(\"parsedFilter\", parsedFilter);\n\n return parsedFilter;\n }\n private setSystemData(itemNew: Partial<T>, action: Action, requestUser?: string | CognitoUser, itemOld?: T): T {\n if (!action || action === Action.DELETE || action === Action.READ) return itemNew as T;\n\n const date = dayjs().toISOString();\n const user = this.extractUser(requestUser);\n\n switch (action) {\n case Action.CREATE:\n return this.handleCreate(itemNew, user, date);\n case Action.UPDATE:\n return this.handleUpdate(itemNew, itemOld, user, date);\n default:\n return itemNew as T;\n }\n }\n\n private extractUser(requestUser?: string | CognitoUser): string {\n if (!requestUser) return \"system\";\n return typeof requestUser === \"string\" ? requestUser : requestUser.username;\n }\n\n private handleCreate(itemNew: Partial<T>, user: string, date: string): T {\n const dayjsData = dayjs(new Date(date));\n itemNew[this.config.DYNAMO_DB.MAP.partitionKey ?? \"id\"] = crypto.randomUUID();\n itemNew.createdAt = date;\n itemNew.createdBy = user;\n itemNew.year = dayjsData.year().toString();\n itemNew.yearMonth = dayjsData.year() + \"-\" + (dayjsData.month() + 1);\n\n if (!this.config.TRACE_CHANGE?.fields) return itemNew as T;\n\n itemNew.history = this.addHistory(itemNew.history, { action: Action.CREATE, user, date });\n return itemNew as T;\n }\n\n private handleUpdate(itemNew: Partial<T>, itemOld: T | undefined, user: string, date: string): T {\n itemNew.createdBy = itemNew.createdBy || itemOld?.createdBy;\n itemNew.updatedBy = itemNew.updatedBy || { username: user };\n itemNew.history = itemNew.history || itemOld?.history;\n\n if (!this.config.TRACE_CHANGE?.fields || !itemOld) return itemNew as T;\n\n delete itemNew.updatedBy;\n\n const changes = computeChangedFields(itemOld, itemNew, this.config.TRACE_CHANGE);\n if (changes.length > 0) {\n itemNew.history = this.addHistory(itemNew.history, {\n action: Action.UPDATE,\n user,\n date,\n changes,\n });\n }\n\n return itemNew as T;\n }\n\n private addHistory(history: ChangeHistory[] | undefined, entry: ChangeHistory): ChangeHistory[] {\n // skip empty or invalid history entries\n if (!entry.changes || entry.changes.length === 0) {\n return history || [];\n }\n\n // clone to avoid accidental mutation\n const newHistory = [...(history || [])];\n\n // optional: limit max history size (e.g., last 100 changes)\n const MAX_HISTORY_ENTRIES = 100;\n if (newHistory.length >= MAX_HISTORY_ENTRIES) {\n newHistory.shift(); // remove oldest\n }\n\n newHistory.push(entry);\n return newHistory;\n }\n\n private setIndexField(filter: Filter, config: EntityConfig) {\n if (!filter.indexName || !filter.indexValue) return filter;\n\n const indexMap = config.DYNAMO_DB.MAP;\n if (!indexMap || indexMap.size === 0) return filter;\n\n const indexConfig = indexMap.get(filter.indexName);\n if (!indexConfig) return filter;\n\n filter.indexName = indexConfig.field;\n }\n}\n"]}
|