aws-service-stack 0.18.404 → 0.18.406
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/_examples/controller/local-task-controller.d.ts +2 -0
- package/dist/_examples/controller/local-task-controller.js +23 -0
- package/dist/_examples/controller/local-task-controller.js.map +1 -0
- package/dist/_examples/model/user.model.d.ts +1 -0
- package/dist/_examples/model/user.model.js +3 -0
- package/dist/_examples/model/user.model.js.map +1 -0
- package/dist/_examples/service/profile-service.js +8 -9
- package/dist/_examples/service/profile-service.js.map +1 -1
- package/dist/exception/errors.js +1 -1
- package/dist/exception/errors.js.map +1 -1
- package/dist/model/dynamodb.model.js.map +1 -1
- package/dist/repositories/base-db.repo.d.ts +1 -0
- package/dist/repositories/base-db.repo.interface.d.ts +12 -0
- package/dist/repositories/base-db.repo.interface.js.map +1 -1
- package/dist/repositories/base-db.repo.js +46 -3
- package/dist/repositories/base-db.repo.js.map +1 -1
- package/dist/service/crud.service.d.ts +1 -0
- package/dist/service/crud.service.interface.d.ts +7 -1
- package/dist/service/crud.service.interface.js.map +1 -1
- package/dist/service/crud.service.js +5 -0
- package/dist/service/crud.service.js.map +1 -1
- package/package.json +10 -6
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
// handler.ts
|
|
7
|
+
require("reflect-metadata");
|
|
8
|
+
const typedi_1 = __importDefault(require("typedi"));
|
|
9
|
+
require("../service/profile-service");
|
|
10
|
+
class HelperCDI {
|
|
11
|
+
profileService = typedi_1.default.get("ProfileService");
|
|
12
|
+
async run() {
|
|
13
|
+
console.log("running");
|
|
14
|
+
await this.entityChanged();
|
|
15
|
+
console.log("done");
|
|
16
|
+
}
|
|
17
|
+
async entityChanged() {
|
|
18
|
+
const profile = await this.profileService.findById("0f761530-9b92-4706-86ab-8bacf311439f");
|
|
19
|
+
log.info(`profile: ${profile.firstName}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
new HelperCDI().run().then((r) => { });
|
|
23
|
+
//# sourceMappingURL=local-task-controller.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local-task-controller.js","sourceRoot":"","sources":["../../../src/_examples/controller/local-task-controller.ts"],"names":[],"mappings":";;;;;AAAA,aAAa;AACb,4BAA0B;AAE1B,oDAA+B;AAE/B,sCAAoC;AAEpC,MAAM,SAAS;IACI,cAAc,GAAmB,gBAAS,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAElF,KAAK,CAAC,GAAG;QACP,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAEvB,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC;QAC3B,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IAEO,KAAK,CAAC,aAAa;QACzB,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,sCAAsC,CAAC,CAAC;QAC3F,GAAG,CAAC,IAAI,CAAC,YAAY,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAC5C,CAAC;CACF;AAED,IAAI,SAAS,EAAE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,GAAE,CAAC,CAAC,CAAC","sourcesContent":["// handler.ts\nimport \"reflect-metadata\";\n\nimport Container from \"typedi\";\nimport { ProfileService } from \"../service/profile-service.interface\";\nimport \"../service/profile-service\";\n\nclass HelperCDI {\n private readonly profileService: ProfileService = Container.get(\"ProfileService\");\n\n async run() {\n console.log(\"running\");\n\n await this.entityChanged();\n console.log(\"done\");\n }\n\n private async entityChanged() {\n const profile = await this.profileService.findById(\"0f761530-9b92-4706-86ab-8bacf311439f\");\n log.info(`profile: ${profile.firstName}`);\n }\n}\n\nnew HelperCDI().run().then((r) => {});\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { User } from "../model-shared/example.model";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"user.model.js","sourceRoot":"","sources":["../../../src/_examples/model/user.model.ts"],"names":[],"mappings":"","sourcesContent":["export { User } from \"../model-shared/example.model\";\n\n"]}
|
|
@@ -13,7 +13,6 @@ exports.ProfileServiceImpl = void 0;
|
|
|
13
13
|
const typedi_1 = require("typedi");
|
|
14
14
|
require("./profile-service");
|
|
15
15
|
require("../repositories/profile/profile-repo-db");
|
|
16
|
-
const errors_1 = require("../../exception/errors");
|
|
17
16
|
const core_1 = require("../../index.js");
|
|
18
17
|
let ProfileServiceImpl = class ProfileServiceImpl extends core_1.CrudServiceImpl {
|
|
19
18
|
constructor() {
|
|
@@ -22,7 +21,7 @@ let ProfileServiceImpl = class ProfileServiceImpl extends core_1.CrudServiceImpl
|
|
|
22
21
|
async deletePhone(profileId) {
|
|
23
22
|
const profile = await this.findById(profileId);
|
|
24
23
|
if (!profile.phone) {
|
|
25
|
-
throw new
|
|
24
|
+
throw new core_1.ErrorHttp({ code: 400, error: "Уг хаяг дээр утасны дугаар байхгүй байна!" });
|
|
26
25
|
}
|
|
27
26
|
try {
|
|
28
27
|
if (profile.oldPhoneNumbers) {
|
|
@@ -37,14 +36,14 @@ let ProfileServiceImpl = class ProfileServiceImpl extends core_1.CrudServiceImpl
|
|
|
37
36
|
return this.save(profile, undefined);
|
|
38
37
|
}
|
|
39
38
|
catch (error) {
|
|
40
|
-
throw new
|
|
39
|
+
throw new core_1.ErrorHttp({ code: 500, error: `Error deleting phone: ${error}` });
|
|
41
40
|
}
|
|
42
41
|
}
|
|
43
42
|
async mergeById(profileIdSource, profileIdTarget) {
|
|
44
43
|
const profileSource = await this.findById(profileIdSource);
|
|
45
44
|
const profileTarget = await this.findById(profileIdTarget);
|
|
46
45
|
if (!profileSource || !profileTarget) {
|
|
47
|
-
throw new
|
|
46
|
+
throw new core_1.ErrorHttp({
|
|
48
47
|
code: 400,
|
|
49
48
|
error: `Тухайн ID дээр профайл олдсонгүй: ${profileSource ? profileIdTarget : profileIdSource}`,
|
|
50
49
|
});
|
|
@@ -54,7 +53,7 @@ let ProfileServiceImpl = class ProfileServiceImpl extends core_1.CrudServiceImpl
|
|
|
54
53
|
return profileTarget;
|
|
55
54
|
}
|
|
56
55
|
catch (error) {
|
|
57
|
-
throw new
|
|
56
|
+
throw new core_1.ErrorHttp({ code: 500, error: `Error merging profiles by ID: ${error}` });
|
|
58
57
|
}
|
|
59
58
|
}
|
|
60
59
|
/**
|
|
@@ -63,7 +62,7 @@ let ProfileServiceImpl = class ProfileServiceImpl extends core_1.CrudServiceImpl
|
|
|
63
62
|
async updateProfileFields(profileId, fieldsToUpdate) {
|
|
64
63
|
const profile = await this.findById(profileId);
|
|
65
64
|
if (!profile) {
|
|
66
|
-
throw new
|
|
65
|
+
throw new core_1.ErrorHttp({ code: 404, error: `Profile not found: ${profileId}` });
|
|
67
66
|
}
|
|
68
67
|
try {
|
|
69
68
|
// Update only the specified fields
|
|
@@ -71,7 +70,7 @@ let ProfileServiceImpl = class ProfileServiceImpl extends core_1.CrudServiceImpl
|
|
|
71
70
|
return this.save(profile, profileId);
|
|
72
71
|
}
|
|
73
72
|
catch (error) {
|
|
74
|
-
throw new
|
|
73
|
+
throw new core_1.ErrorHttp({ code: 500, error: `Error updating profile fields: ${error}` });
|
|
75
74
|
}
|
|
76
75
|
}
|
|
77
76
|
// Override findAll to return all profiles
|
|
@@ -81,13 +80,13 @@ let ProfileServiceImpl = class ProfileServiceImpl extends core_1.CrudServiceImpl
|
|
|
81
80
|
return result.items || [];
|
|
82
81
|
}
|
|
83
82
|
catch (error) {
|
|
84
|
-
throw new
|
|
83
|
+
throw new core_1.ErrorHttp({ code: 500, error: `Error fetching all profiles: ${error}` });
|
|
85
84
|
}
|
|
86
85
|
}
|
|
87
86
|
async mergeProfile(from, to) {
|
|
88
87
|
// Merge logic - simplified version of the original
|
|
89
88
|
if (from.cardNumber && to.cardNumber && from.cardNumber !== to.cardNumber) {
|
|
90
|
-
throw new
|
|
89
|
+
throw new core_1.ErrorHttp({ code: 400, error: "Profiles cannot merge with different card numbers" });
|
|
91
90
|
}
|
|
92
91
|
if (from.cardNumber)
|
|
93
92
|
to.cardNumber = from.cardNumber;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"profile-service.js","sourceRoot":"","sources":["../../../src/_examples/service/profile-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAA4C;AAE5C,6BAA2B;AAE3B,mDAAiD;AAEjD,mDAAmD;AACnD,yCAAiD;AAI1C,IAAM,kBAAkB,GAAxB,MAAM,kBAAmB,SAAQ,sBAA4C;IAClF;QACE,KAAK,CAAC,kBAAS,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,IAAI,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,SAAiB;QACjC,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QAC/C,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;YACnB,MAAM,IAAI,kBAAS,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,2CAA2C,EAAE,CAAC,CAAC;QACzF,CAAC;QACD,IAAI,CAAC;YACH,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;gBAC5B,OAAO,CAAC,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC9C,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,eAAe,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC5C,CAAC;YAED,OAAO,OAAO,CAAC,KAAK,CAAC;YACrB,OAAO,OAAO,CAAC,aAAa,CAAC;YAC7B,OAAO,OAAO,CAAC,qBAAqB,CAAC;YAErC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AAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;CACF,CAAA;AAxIY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,gBAAO,EAAC,gBAAgB,CAAC;;GACb,kBAAkB,CAwI9B","sourcesContent":["import { Container, Service } from \"typedi\";\nimport { ProfileService } from \"./profile-service.interface\";\nimport \"./profile-service\";\nimport { ProfileRepoDB } from \"../repositories/profile/profile-repo-db.interface\";\nimport \"../repositories/profile/profile-repo-db\";\n\nimport { ErrorHttp } from \"../../exception/errors\";\nimport { CrudServiceImpl } from \"@chinggis/core\";\nimport { Profile } from \"../model-shared/example.model\";\n\n@Service(\"ProfileService\")\nexport class ProfileServiceImpl extends CrudServiceImpl<Profile, ProfileRepoDB, any> implements ProfileService {\n constructor() {\n super(Container.get(\"ProfileRepoDB\"), null);\n }\n\n async deletePhone(profileId: string): Promise<Profile> {\n const profile = await this.findById(profileId);\n if (!profile.phone) {\n throw new ErrorHttp({ code: 400, error: \"Уг хаяг дээр утасны дугаар байхгүй байна!\" });\n }\n try {\n if (profile.oldPhoneNumbers) {\n profile.oldPhoneNumbers.push(profile.phone);\n } else {\n profile.oldPhoneNumbers = [profile.phone];\n }\n\n delete profile.phone;\n delete profile.phoneVerified;\n delete profile.phoneVerificationCode;\n\n return this.save(profile, undefined);\n } catch (error) {\n throw new ErrorHttp({ code: 500, error: `Error deleting phone: ${error}` });\n }\n }\n\n async mergeById(profileIdSource: string, profileIdTarget: string): Promise<Profile> {\n const profileSource = await this.findById(profileIdSource);\n const profileTarget = await this.findById(profileIdTarget);\n\n if (!profileSource || !profileTarget) {\n throw new ErrorHttp({\n code: 400,\n error: `Тухайн ID дээр профайл олдсонгүй: ${profileSource ? profileIdTarget : profileIdSource}`,\n });\n }\n try {\n await this.mergeProfile(profileSource, profileTarget);\n return profileTarget;\n } catch (error) {\n throw new ErrorHttp({ code: 500, error: `Error merging profiles by ID: ${error}` });\n }\n }\n\n /**\n * Example method showing PATCH validation (only specific fields)\n */\n async updateProfileFields(profileId: string, fieldsToUpdate: Partial<Profile>): Promise<Profile> {\n const profile = await this.findById(profileId);\n if (!profile) {\n throw new ErrorHttp({ code: 404, error: `Profile not found: ${profileId}` });\n }\n try {\n // Update only the specified fields\n Object.assign(profile, fieldsToUpdate);\n\n return this.save(profile, profileId);\n } catch (error) {\n throw new ErrorHttp({ code: 500, error: `Error updating profile fields: ${error}` });\n }\n }\n\n // Override findAll to return all profiles\n async findAll(): Promise<Profile[]> {\n try {\n const result = await this.scan({});\n return (result.items as Profile[]) || [];\n } catch (error) {\n throw new ErrorHttp({ code: 500, error: `Error fetching all profiles: ${error}` });\n }\n }\n\n private async mergeProfile(from: Partial<Profile>, to: Partial<Profile>): Promise<void> {\n // Merge logic - simplified version of the original\n if (from.cardNumber && to.cardNumber && from.cardNumber !== to.cardNumber) {\n throw new ErrorHttp({ code: 400, error: \"Profiles cannot merge with different card numbers\" });\n }\n\n if (from.cardNumber) to.cardNumber = from.cardNumber;\n if (from.availablePoint) {\n to.availablePoint = to.availablePoint ? to.availablePoint + from.availablePoint : from.availablePoint;\n }\n if (from.providerIds) to.providerIds = this.mergeArrays(to.providerIds || [], from.providerIds);\n if (from.boughtEntityIds) to.boughtEntityIds = this.mergeArrays(to.boughtEntityIds || [], from.boughtEntityIds);\n if (from.loyaltyPercentage && from.loyaltyPercentage > (to.loyaltyPercentage || 0)) {\n to.loyaltyPercentage = from.loyaltyPercentage;\n }\n if (from.email && !to.email) to.email = from.email;\n if (from.firstName && !to.firstName) to.firstName = from.firstName;\n if (from.lastName && !to.lastName) to.lastName = from.lastName;\n if (from.birthDate && !to.birthDate) to.birthDate = from.birthDate;\n if (from.gender && !to.gender) to.gender = from.gender;\n if (from.facebook && !to.facebook) to.facebook = from.facebook;\n if (from.google && !to.google) to.google = from.google;\n if (from.apple && !to.apple) to.apple = from.apple;\n if (from.phone && !to.phone) to.phone = from.phone;\n if (from.cardPin && !to.cardPin) to.cardPin = from.cardPin;\n if (from.emailVerified) to.emailVerified = from.emailVerified;\n if (from.phoneVerified) {\n to.phoneVerified = true;\n delete to.toVerifyPhone;\n }\n\n if (from.oldPhoneNumbers) {\n to.oldPhoneNumbers = this.mergeArrays(to.oldPhoneNumbers || [], from.oldPhoneNumbers);\n if (from.phone) to.oldPhoneNumbers.push(from.phone);\n }\n\n this.addNote(to, `${from.id} id-тай бүртгэлийг энэ бүртгэлтэй нэгтгэв. date: ${new Date().toISOString()}`);\n this.markAsRemoved(from);\n\n await this.saveAll([from, to], \"core.system\", \"services\");\n }\n\n private addNote(profile: Partial<Profile>, note: string): void {\n if (!profile.note) profile.note = \"\";\n profile.note = profile.note ? `${profile.note}\\n${note}` : note;\n }\n\n private markAsRemoved(profile: Partial<Profile>): void {\n if (profile.phone) profile.phone = `removed_${profile.phone}`;\n if (profile.email) profile.email = `removed_${profile.email}`;\n if (profile.firstName) profile.firstName = `removed_${profile.firstName}`;\n if (profile.lastName) profile.lastName = `removed_${profile.lastName}`;\n if (profile.providerIds && profile.providerIds.length > 0) {\n profile.providerIds = profile.providerIds.map((id) => \"removed_\" + id);\n }\n }\n\n private mergeArrays(target: any[], source: any[]): any[] {\n if (!Array.isArray(target)) {\n return [...source];\n }\n return [...target, ...source.filter((item) => !target.includes(item))];\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"profile-service.js","sourceRoot":"","sources":["../../../src/_examples/service/profile-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAA4C;AAE5C,6BAA2B;AAE3B,mDAAiD;AAEjD,yCAA4D;AAIrD,IAAM,kBAAkB,GAAxB,MAAM,kBAAmB,SAAQ,sBAA4C;IAClF;QACE,KAAK,CAAC,kBAAS,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,IAAI,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,SAAiB;QACjC,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QAC/C,IAAI,CAAC,OAA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,OAAO,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC1D,OAAO,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC;QACzE,CAAC;IACH,CAAC;IAEO,WAAW,CAAC,MAAa,EAAE,MAAa;QAC9C,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YAC3B,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC;QACrB,CAAC;QACD,OAAO,CAAC,GAAG,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;CACF,CAAA;AAxIY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,gBAAO,EAAC,gBAAgB,CAAC;;GACb,kBAAkB,CAwI9B","sourcesContent":["import { Container, Service } from \"typedi\";\nimport { ProfileService } from \"./profile-service.interface\";\nimport \"./profile-service\";\nimport { ProfileRepoDB } from \"../repositories/profile/profile-repo-db.interface\";\nimport \"../repositories/profile/profile-repo-db\";\n\nimport { CrudServiceImpl, ErrorHttp } from \"@chinggis/core\";\nimport { Profile } from \"../model-shared/example.model\";\n\n@Service(\"ProfileService\")\nexport class ProfileServiceImpl extends CrudServiceImpl<Profile, ProfileRepoDB, any> implements ProfileService {\n constructor() {\n super(Container.get(\"ProfileRepoDB\"), null);\n }\n\n async deletePhone(profileId: string): Promise<Profile> {\n const profile = await this.findById(profileId);\n if (!profile.phone) {\n throw new ErrorHttp({ code: 400, error: \"Уг хаяг дээр утасны дугаар байхгүй байна!\" });\n }\n try {\n if (profile.oldPhoneNumbers) {\n profile.oldPhoneNumbers.push(profile.phone);\n } else {\n profile.oldPhoneNumbers = [profile.phone];\n }\n\n delete profile.phone;\n delete profile.phoneVerified;\n delete profile.phoneVerificationCode;\n\n return this.save(profile, undefined);\n } catch (error) {\n throw new ErrorHttp({ code: 500, error: `Error deleting phone: ${error}` });\n }\n }\n\n async mergeById(profileIdSource: string, profileIdTarget: string): Promise<Profile> {\n const profileSource = await this.findById(profileIdSource);\n const profileTarget = await this.findById(profileIdTarget);\n\n if (!profileSource || !profileTarget) {\n throw new ErrorHttp({\n code: 400,\n error: `Тухайн ID дээр профайл олдсонгүй: ${profileSource ? profileIdTarget : profileIdSource}`,\n });\n }\n try {\n await this.mergeProfile(profileSource, profileTarget);\n return profileTarget;\n } catch (error) {\n throw new ErrorHttp({ code: 500, error: `Error merging profiles by ID: ${error}` });\n }\n }\n\n /**\n * Example method showing PATCH validation (only specific fields)\n */\n async updateProfileFields(profileId: string, fieldsToUpdate: Partial<Profile>): Promise<Profile> {\n const profile = await this.findById(profileId);\n if (!profile) {\n throw new ErrorHttp({ code: 404, error: `Profile not found: ${profileId}` });\n }\n try {\n // Update only the specified fields\n Object.assign(profile, fieldsToUpdate);\n\n return this.save(profile, profileId);\n } catch (error) {\n throw new ErrorHttp({ code: 500, error: `Error updating profile fields: ${error}` });\n }\n }\n\n // Override findAll to return all profiles\n async findAll(): Promise<Profile[]> {\n try {\n const result = await this.scan({});\n return (result.items as Profile[]) || [];\n } catch (error) {\n throw new ErrorHttp({ code: 500, error: `Error fetching all profiles: ${error}` });\n }\n }\n\n private async mergeProfile(from: Partial<Profile>, to: Partial<Profile>): Promise<void> {\n // Merge logic - simplified version of the original\n if (from.cardNumber && to.cardNumber && from.cardNumber !== to.cardNumber) {\n throw new ErrorHttp({ code: 400, error: \"Profiles cannot merge with different card numbers\" });\n }\n\n if (from.cardNumber) to.cardNumber = from.cardNumber;\n if (from.availablePoint) {\n to.availablePoint = to.availablePoint ? to.availablePoint + from.availablePoint : from.availablePoint;\n }\n if (from.providerIds) to.providerIds = this.mergeArrays(to.providerIds || [], from.providerIds);\n if (from.boughtEntityIds) to.boughtEntityIds = this.mergeArrays(to.boughtEntityIds || [], from.boughtEntityIds);\n if (from.loyaltyPercentage && from.loyaltyPercentage > (to.loyaltyPercentage || 0)) {\n to.loyaltyPercentage = from.loyaltyPercentage;\n }\n if (from.email && !to.email) to.email = from.email;\n if (from.firstName && !to.firstName) to.firstName = from.firstName;\n if (from.lastName && !to.lastName) to.lastName = from.lastName;\n if (from.birthDate && !to.birthDate) to.birthDate = from.birthDate;\n if (from.gender && !to.gender) to.gender = from.gender;\n if (from.facebook && !to.facebook) to.facebook = from.facebook;\n if (from.google && !to.google) to.google = from.google;\n if (from.apple && !to.apple) to.apple = from.apple;\n if (from.phone && !to.phone) to.phone = from.phone;\n if (from.cardPin && !to.cardPin) to.cardPin = from.cardPin;\n if (from.emailVerified) to.emailVerified = from.emailVerified;\n if (from.phoneVerified) {\n to.phoneVerified = true;\n delete to.toVerifyPhone;\n }\n\n if (from.oldPhoneNumbers) {\n to.oldPhoneNumbers = this.mergeArrays(to.oldPhoneNumbers || [], from.oldPhoneNumbers);\n if (from.phone) to.oldPhoneNumbers.push(from.phone);\n }\n\n this.addNote(to, `${from.id} id-тай бүртгэлийг энэ бүртгэлтэй нэгтгэв. date: ${new Date().toISOString()}`);\n this.markAsRemoved(from);\n\n await this.saveAll([from, to], \"core.system\", \"services\");\n }\n\n private addNote(profile: Partial<Profile>, note: string): void {\n if (!profile.note) profile.note = \"\";\n profile.note = profile.note ? `${profile.note}\\n${note}` : note;\n }\n\n private markAsRemoved(profile: Partial<Profile>): void {\n if (profile.phone) profile.phone = `removed_${profile.phone}`;\n if (profile.email) profile.email = `removed_${profile.email}`;\n if (profile.firstName) profile.firstName = `removed_${profile.firstName}`;\n if (profile.lastName) profile.lastName = `removed_${profile.lastName}`;\n if (profile.providerIds && profile.providerIds.length > 0) {\n profile.providerIds = profile.providerIds.map((id) => \"removed_\" + id);\n }\n }\n\n private mergeArrays(target: any[], source: any[]): any[] {\n if (!Array.isArray(target)) {\n return [...source];\n }\n return [...target, ...source.filter((item) => !target.includes(item))];\n }\n}\n"]}
|
package/dist/exception/errors.js
CHANGED
|
@@ -30,8 +30,8 @@ class ErrorHttp extends Error {
|
|
|
30
30
|
constructor(errorCodeMsg, errorMessage, errorData) {
|
|
31
31
|
super(errorData);
|
|
32
32
|
this.statusCode = errorCodeMsg.code;
|
|
33
|
-
this.message = typeof errorMessage === "object" ? JSON.stringify(errorMessage) : errorMessage;
|
|
34
33
|
this.error = errorCodeMsg.error;
|
|
34
|
+
this.message = typeof errorMessage === "object" ? JSON.stringify(errorMessage) : errorMessage;
|
|
35
35
|
this.data = errorData;
|
|
36
36
|
}
|
|
37
37
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/exception/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,SAAU,SAAQ,KAAK;IAClC,IAAI,CAAS;IACb,OAAO,CAAS;IAChB,KAAK,CAAM;IACX,YAAY,IAAY,EAAE,OAAe,EAAE,YAAkB;QAC3D,KAAK,CAAC,YAAY,CAAC,CAAC;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AATD,8BASC;AAED,MAAa,aAAc,SAAQ,KAAK;IACtC,SAAS,CAAS;IAClB,OAAO,CAAM;IACb,YAAY,SAAiB,EAAE,OAAY,EAAE,YAAkB;QAC7D,KAAK,CAAC,YAAY,CAAC,CAAC;QACpB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AARD,sCAQC;AAOD,MAAa,SAAU,SAAQ,KAAK;IAClC,UAAU,CAAS;IACnB,KAAK,CAAS;IACd,OAAO,CAAS;IAChB,IAAI,CAAM;IAEV,YAAY,YAA0B,EAAE,YAAkB,EAAE,SAAe;QACzE,KAAK,CAAC,SAAS,CAAC,CAAC;QACjB,IAAI,CAAC,UAAU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AAC;QAC9F,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC;IACxB,CAAC;CACF;AAbD,8BAaC;AAED,MAAa,eAAgB,SAAQ,KAAK;IACxC,UAAU,CAAS;IACnB,UAAU,CAAmB;IAC7B,KAAK,CAAM;IACX,OAAO,CAAM;IAEb,YAAY,UAAkB,EAAE,UAA4B,EAAE,YAAkB;QAC9E,KAAK,CAAC,YAAY,CAAC,CAAC;QACpB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,YAAY,CAAC;IAC9B,CAAC;CACF;AAZD,0CAYC;AAED,MAAa,qBAAsB,SAAQ,KAAK;IAC9C,YAAY,SAAiB;QAC3B,KAAK,CAAC,GAAG,SAAS,eAAe,CAAC,CAAC;QACnC,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAC;IACtC,CAAC;CACF;AALD,sDAKC","sourcesContent":["export class ErrorBase extends Error {\n code: number;\n message: string;\n error: any;\n constructor(code: number, message: string, errorContent?: any) {\n super(errorContent);\n this.code = code;\n this.message = message;\n }\n}\n\nexport class ErrorDynamoDB extends Error {\n tableName: string;\n command: any;\n constructor(tableName: string, command: any, errorContent?: any) {\n super(errorContent);\n this.tableName = tableName;\n this.command = command;\n }\n}\n\nexport interface ErrorCodeMsg {\n code: number;\n error: string;\n}\n\nexport class ErrorHttp extends Error {\n statusCode: number;\n error: string;\n message: string;\n data: any;\n\n constructor(errorCodeMsg: ErrorCodeMsg, errorMessage?: any, errorData?: any) {\n super(errorData);\n this.statusCode = errorCodeMsg.code;\n this.error = errorCodeMsg.error;\n this.message = typeof errorMessage === \"object\" ? JSON.stringify(errorMessage) : errorMessage;\n this.data = errorData;\n }\n}\n\nexport class ErrorValidation extends Error {\n entityName: string;\n validation: Map<string, any>;\n error: any;\n content: any;\n\n constructor(entityName: string, validation: Map<string, any>, errorContent?: any) {\n super(errorContent);\n this.entityName = entityName;\n this.validation = validation;\n this.content = errorContent;\n }\n}\n\nexport class MissingParameterError extends Error {\n constructor(paramName: string) {\n super(`${paramName} is required.`);\n this.name = \"MissingParameterError\";\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamodb.model.js","sourceRoot":"","sources":["../../src/model/dynamodb.model.ts"],"names":[],"mappings":";;;AAAA,IAAY,cAIX;AAJD,WAAY,cAAc;IACxB,mCAAiB,CAAA;IACjB,mCAAiB,CAAA;IACjB,mCAAiB,CAAA;AACnB,CAAC,EAJW,cAAc,8BAAd,cAAc,QAIzB;
|
|
1
|
+
{"version":3,"file":"dynamodb.model.js","sourceRoot":"","sources":["../../src/model/dynamodb.model.ts"],"names":[],"mappings":";;;AAAA,IAAY,cAIX;AAJD,WAAY,cAAc;IACxB,mCAAiB,CAAA;IACjB,mCAAiB,CAAA;IACjB,mCAAiB,CAAA;AACnB,CAAC,EAJW,cAAc,8BAAd,cAAc,QAIzB;AAsBD,oFAAoF;AACpF,MAAa,cAAe,SAAQ,GAQnC;IACC,YAAY,GAAW,IAAI,CAAC;IAC5B,YAAY,CAAY;IACxB,UAAU,CAAY;IACtB,SAAS,CAAY;IACrB,aAAa,CAAY;IAEzB,SAAS,CACP,YAAqB,EACrB,YAAuB,EACvB,WAAsB,EACtB,aAAwB,EACxB,SAAoB;QAEpB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,UAAU,GAAG,WAAW,CAAC;QAC9B,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA7BD,wCA6BC","sourcesContent":["export enum ActionDynamoDB {\n INSERT = \"INSERT\",\n MODIFY = \"MODIFY\",\n REMOVE = \"REMOVE\",\n}\n\n\nexport interface DynamoDbFilter {\n keyConditionExpression?: string;\n filterExpression?: string;\n expressionAttributeNames?: { [key: string]: string };\n expressionAttributeValues?: { [key: string]: any };\n scanIndexForward?: boolean; // false for descending order, true for ascending order\n size?: number;\n startAt?: string;\n getAllItems?: boolean;\n}\n\n/*\n * @deprecated use List\n * **/\nexport interface DynamoDbListResponse<T> {\n items: Array<T>;\n lastKey?: string;\n}\n\n/** the map key is indexName, field: indexField, rField: related field names list */\nexport class DynamoIndexMap extends Map<\n string,\n {\n field: string;\n rFields: string[];\n sortKeyField?: string;\n fieldSeparator?: string;\n }\n> {\n partitionKey: string = \"id\";\n numberFields?: string[];\n listFields?: string[];\n mapFields?: string[];\n booleanFields?: string[];\n\n setFields(\n partitionKey?: string,\n numberFields?: string[],\n arrayFields?: string[],\n booleanFields?: string[],\n mapFields?: string[],\n ): this {\n this.partitionKey = partitionKey;\n this.numberFields = numberFields;\n this.listFields = arrayFields;\n this.booleanFields = booleanFields;\n this.mapFields = mapFields;\n return this;\n }\n}\n"]}
|
|
@@ -11,6 +11,7 @@ export declare class BaseRepoDBImpl<T extends BaseEntity> implements BaseRepoDB<
|
|
|
11
11
|
decrementValueByField(entityId: string, fieldName: string, value?: number, nestedFieldSeparator?: string): Promise<T>;
|
|
12
12
|
transactWrite?(operations: any[]): Promise<boolean>;
|
|
13
13
|
update(entity: Partial<T>): Promise<T>;
|
|
14
|
+
updateFields(entity: Partial<T>, fields: string[]): Promise<Partial<T>>;
|
|
14
15
|
updateMany(entityList: Partial<T>[], fields: string[], isTransactional: boolean): Promise<boolean>;
|
|
15
16
|
save(entity: Partial<T>): Promise<T>;
|
|
16
17
|
saveMany(entities: Partial<T>[], isTransactional?: boolean): Promise<Partial<T>[]>;
|
|
@@ -25,6 +25,17 @@ export interface BaseRepoDB<T extends BaseEntity> extends CoreRepo<T> {
|
|
|
25
25
|
* @returns The updated entity.
|
|
26
26
|
*/
|
|
27
27
|
update(entity: Partial<T>): Promise<T>;
|
|
28
|
+
/**
|
|
29
|
+
* Updates only selected fields of one entity identified by its partition key.
|
|
30
|
+
* Supports nested paths using dot notation (e.g. `author.name`).
|
|
31
|
+
*
|
|
32
|
+
* This is a convenience wrapper over `updateMany` for single-item updates.
|
|
33
|
+
*
|
|
34
|
+
* @param entityId - Partition key value of the entity.
|
|
35
|
+
* @param fields - Field names that should be updated.
|
|
36
|
+
* @returns True if the update request is accepted; otherwise, false.
|
|
37
|
+
*/
|
|
38
|
+
updateFields(entity: Partial<T>, fields: string[]): Promise<Partial<T>>;
|
|
28
39
|
/**
|
|
29
40
|
* Updates multiple existing entities.
|
|
30
41
|
*
|
|
@@ -35,6 +46,7 @@ export interface BaseRepoDB<T extends BaseEntity> extends CoreRepo<T> {
|
|
|
35
46
|
* If `fieldNames` **is provided**, each entity is updated individually, and only the
|
|
36
47
|
* specified fields in `fieldNames` will be modified. This approach avoids overwriting
|
|
37
48
|
* the entire entity and is useful for partial updates.
|
|
49
|
+
* Field names support dot notation for nested updates (e.g. `author.name`).
|
|
38
50
|
*
|
|
39
51
|
* Note:
|
|
40
52
|
* - Entities must already exist in the data store.
|
|
@@ -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 /** Executes a DynamoDB Scan with optional non-index filters. */\n scan(filter: Filter): Promise<List<Partial<T>>>;\n\n /**\n * Atomically increments a numeric field. Supports nested map attributes via `nestedFieldSeparator`.\n * Initializes to `0` if the field does not exist. Leaf field must be in `indexMap.numberFields`.\n *\n * @param entityId - Partition key of the item.\n * @param fieldName - Field name or separator-delimited path (e.g. `\"stats.views\"`).\n * @param value - Amount to increment. Defaults to `1`. Must be positive.\n * @param nestedFieldSeparator - If provided, splits `fieldName` into a nested path.\n *\n * @example\n * repo.incrementValueByField(id, \"views\");\n * repo.incrementValueByField(id, \"stats.monthly.views\", 5, \".\");\n */\n incrementValueByField(entityId: string, fieldName: string, value?: number, nestedFieldSeparator?: string): Promise<T>;\n\n /**\n * Atomically decrements a numeric field. Supports nested map attributes via `nestedFieldSeparator`.\n * Initializes to `0` if the field does not exist. Leaf field must be in `indexMap.numberFields`.\n *\n * @param entityId - Partition key of the item.\n * @param fieldName - Field name or separator-delimited path (e.g. `\"stats.stock\"`).\n * @param value - Amount to decrement. Defaults to `-1`. Must be negative.\n * @param nestedFieldSeparator - If provided, splits `fieldName` into a nested path.\n *\n * @example\n * repo.decrementValueByField(id, \"stock\");\n * repo.decrementValueByField(id, \"stats.monthly.stock\", -3, \".\");\n */\n decrementValueByField(entityId: string, fieldName: string, value?: number, nestedFieldSeparator?: string): Promise<T>;\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 only selected fields of one entity identified by its partition key.\n * Supports nested paths using dot notation (e.g. `author.name`).\n *\n * This is a convenience wrapper over `updateMany` for single-item updates.\n *\n * @param entityId - Partition key value of the entity.\n * @param fields - Field names that should be updated.\n * @returns True if the update request is accepted; otherwise, false.\n */\n updateFields(entity: Partial<T>, fields: string[]): Promise<Partial<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 * Field names support dot notation for nested updates (e.g. `author.name`).\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 /**\n * Atomically increments a numeric field. Supports nested map attributes via `nestedFieldSeparator`.\n * Initializes to `0` if the field does not exist. Leaf field must be in `indexMap.numberFields`.\n *\n * @param entityId - Partition key of the item.\n * @param fieldName - Field name or separator-delimited path (e.g. `\"stats.views\"`).\n * @param value - Amount to increment. Defaults to `1`. Must be positive.\n * @param nestedFieldSeparator - If provided, splits `fieldName` into a nested path.\n *\n * @example\n * repo.incrementValueByField(id, \"views\");\n * repo.incrementValueByField(id, \"stats.monthly.views\", 5, \".\");\n */\n incrementValueByField(entityId: string, fieldName: string, value?: number, nestedFieldSeparator?: string): Promise<T>;\n\n /**\n * Atomically decrements a numeric field. Supports nested map attributes via `nestedFieldSeparator`.\n * Initializes to `0` if the field does not exist. Leaf field must be in `indexMap.numberFields`.\n *\n * @param entityId - Partition key of the item.\n * @param fieldName - Field name or separator-delimited path (e.g. `\"stats.stock\"`).\n * @param value - Amount to decrement. Defaults to `-1`. Must be negative.\n * @param nestedFieldSeparator - If provided, splits `fieldName` into a nested path.\n *\n * @example\n * repo.decrementValueByField(id, \"stock\");\n * repo.decrementValueByField(id, \"stats.monthly.stock\", -3, \".\");\n */\n decrementValueByField(entityId: string, fieldName: string, value?: number, nestedFieldSeparator?: string): Promise<T>;\n}\n"]}
|
|
@@ -112,6 +112,49 @@ class BaseRepoDBImpl {
|
|
|
112
112
|
}
|
|
113
113
|
return (0, util_dynamodb_1.unmarshall)(result.Attributes);
|
|
114
114
|
}
|
|
115
|
+
async updateFields(entity, fields) {
|
|
116
|
+
if (!entity || !fields?.length)
|
|
117
|
+
return entity;
|
|
118
|
+
const partitionKey = this._indexMap?.partitionKey;
|
|
119
|
+
if (!partitionKey)
|
|
120
|
+
return entity;
|
|
121
|
+
const entityId = entity[partitionKey];
|
|
122
|
+
if (!entityId)
|
|
123
|
+
return entity;
|
|
124
|
+
const updateExpressions = [];
|
|
125
|
+
const expressionAttributeNames = {};
|
|
126
|
+
const expressionAttributeValues = {}; // Typ je nach deinem SDK Import
|
|
127
|
+
fields.forEach((fieldPath, index) => {
|
|
128
|
+
if (fieldPath === partitionKey)
|
|
129
|
+
return;
|
|
130
|
+
const rawValue = fieldPath.split(".").reduce((acc, part) => acc?.[part], entity);
|
|
131
|
+
if (rawValue === undefined)
|
|
132
|
+
return;
|
|
133
|
+
const parts = fieldPath.split(".");
|
|
134
|
+
const pathPlaceholders = [];
|
|
135
|
+
parts.forEach((part, partIndex) => {
|
|
136
|
+
const namePlaceholder = `#field${index}_${partIndex}`;
|
|
137
|
+
pathPlaceholders.push(namePlaceholder);
|
|
138
|
+
expressionAttributeNames[namePlaceholder] = part; // Mappt z.B. "#field0_0" auf "loyalty"
|
|
139
|
+
});
|
|
140
|
+
const fullPath = pathPlaceholders.join(".");
|
|
141
|
+
const valuePlaceholder = `:val${index}`;
|
|
142
|
+
updateExpressions.push(`${fullPath} = ${valuePlaceholder}`);
|
|
143
|
+
const marshalledWrapper = (0, util_dynamodb_1.marshall)({ temp: rawValue }, { removeUndefinedValues: true });
|
|
144
|
+
expressionAttributeValues[valuePlaceholder] = marshalledWrapper.temp;
|
|
145
|
+
});
|
|
146
|
+
if (updateExpressions.length === 0)
|
|
147
|
+
return entity;
|
|
148
|
+
const response = await this.dynamoDb.send(new client_dynamodb_1.UpdateItemCommand({
|
|
149
|
+
TableName: this._tableName,
|
|
150
|
+
Key: (0, util_dynamodb_1.marshall)({ [partitionKey]: entityId }),
|
|
151
|
+
UpdateExpression: `SET ${updateExpressions.join(", ")}`,
|
|
152
|
+
ExpressionAttributeNames: expressionAttributeNames,
|
|
153
|
+
ExpressionAttributeValues: expressionAttributeValues,
|
|
154
|
+
ReturnValues: client_dynamodb_1.ReturnValue.ALL_NEW,
|
|
155
|
+
}));
|
|
156
|
+
return response.Attributes ? (0, util_dynamodb_1.unmarshall)(response.Attributes) : entity;
|
|
157
|
+
}
|
|
115
158
|
async updateMany(entityList, fields, isTransactional) {
|
|
116
159
|
if (isTransactional === undefined || isTransactional === false || isTransactional === null)
|
|
117
160
|
return await this.updateManyNormal(entityList, fields);
|
|
@@ -349,15 +392,15 @@ class BaseRepoDBImpl {
|
|
|
349
392
|
return true;
|
|
350
393
|
}
|
|
351
394
|
const partitionKey = this._indexMap.partitionKey;
|
|
352
|
-
|
|
353
|
-
const entityListCleaned = (0, index_1.removeFields)(entityList,
|
|
395
|
+
const selectedFields = Array.from(new Set([...(fieldNames || []), partitionKey]));
|
|
396
|
+
const entityListCleaned = (0, index_1.removeFields)(entityList, selectedFields);
|
|
354
397
|
const indexedItems = entityListCleaned.map((entity) => {
|
|
355
398
|
return (0, index_1.addIndexValue)(entity, this._indexMap);
|
|
356
399
|
});
|
|
357
400
|
const transactItems = indexedItems
|
|
358
401
|
.map((item) => {
|
|
359
402
|
if (!item[partitionKey])
|
|
360
|
-
throw new Error(`Item must have an ${partitionKey} field. Entity: ${JSON.stringify(item, null, 2)}, \nupdateFields: ${JSON.stringify(
|
|
403
|
+
throw new Error(`Item must have an ${partitionKey} field. Entity: ${JSON.stringify(item, null, 2)}, \nupdateFields: ${JSON.stringify(selectedFields)}`);
|
|
361
404
|
const { UpdateExpression, ExpressionAttributeNames, ExpressionAttributeValues } = (0, index_1.buildUpdateExpressions)(item, [
|
|
362
405
|
partitionKey,
|
|
363
406
|
]);
|
|
@@ -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,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;QAED,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC;QACjD,MAAM,wBAAwB,GAA2B,EAAE,CAAC;QAC5D,MAAM,iBAAiB,GAAa,EAAE,CAAC;QAEvC,KAAK,MAAM,KAAK,IAAI,UAAU,EAAE,CAAC;YAC/B,MAAM,WAAW,GAAG,IAAI,KAAK,EAAE,CAAC;YAChC,wBAAwB,CAAC,WAAW,CAAC,GAAG,KAAK,CAAC;YAC9C,iBAAiB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACtC,CAAC;QAED,MAAM,gBAAgB,GAAG,UAAU,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAElE,MAAM,MAAM,GAAG;YACb,SAAS,EAAE,IAAI,CA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AAC;IACH,CAAC;CACF;AA/lBD,wCA+lBC","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, nestedFieldSeparator?: string): Promise<T> {\n if (value < 0) {\n throw new Error(\"Increment operation only supports positive values\");\n }\n const fieldPath = nestedFieldSeparator ? fieldName.split(nestedFieldSeparator) : [fieldName];\n return this.incrementOrDecrementFieldValue(entityId, fieldPath, value ?? 1);\n }\n\n decrementValueByField(entityId: string, fieldName: string, value?: number, nestedFieldSeparator?: string): 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 const fieldPath = nestedFieldSeparator ? fieldName.split(nestedFieldSeparator) : [fieldName];\n return this.incrementOrDecrementFieldValue(entityId, fieldPath, 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, fieldPath: string[], delta: number): Promise<T> {\n const partitionKey = this._indexMap.partitionKey;\n const leafField = fieldPath[fieldPath.length - 1];\n\n if (!this?._indexMap?.numberFields?.includes(leafField)) {\n throw new Error(`${leafField} field not found in indexMap.numberFields`);\n }\n\n const expressionAttributeNames: Record<string, string> = {};\n fieldPath.forEach((segment, i) => {\n expressionAttributeNames[`#f${i}`] = segment;\n });\n\n const pathExpr = fieldPath.map((_, i) => `#f${i}`).join(\".\");\n\n const params: UpdateItemCommandInput = {\n TableName: this._tableName,\n Key: marshall({ [partitionKey]: entityId }),\n UpdateExpression: `SET ${pathExpr} = if_not_exists(${pathExpr}, :start) + :delta`,\n ExpressionAttributeNames: expressionAttributeNames,\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":[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AkD;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;AA9pBD,wCA8pBC","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(\n entityId: string,\n fieldName: string,\n value?: number,\n nestedFieldSeparator?: string,\n ): Promise<T> {\n if (value < 0) {\n throw new Error(\"Increment operation only supports positive values\");\n }\n const fieldPath = nestedFieldSeparator ? fieldName.split(nestedFieldSeparator) : [fieldName];\n return this.incrementOrDecrementFieldValue(entityId, fieldPath, value ?? 1);\n }\n\n decrementValueByField(\n entityId: string,\n fieldName: string,\n value?: number,\n nestedFieldSeparator?: string,\n ): 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 const fieldPath = nestedFieldSeparator ? fieldName.split(nestedFieldSeparator) : [fieldName];\n return this.incrementOrDecrementFieldValue(entityId, fieldPath, 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 updateFields(entity: Partial<T>, fields: string[]): Promise<Partial<T>> {\n if (!entity || !fields?.length) return entity;\n\n const partitionKey = this._indexMap?.partitionKey;\n if (!partitionKey) return entity;\n\n const entityId = entity[partitionKey as keyof T] as unknown as string;\n if (!entityId) return entity;\n\n const updateExpressions: string[] = [];\n const expressionAttributeNames: Record<string, string> = {};\n const expressionAttributeValues: Record<string, any> = {}; // Typ je nach deinem SDK Import\n\n fields.forEach((fieldPath, index) => {\n if (fieldPath === partitionKey) return;\n\n const rawValue = fieldPath.split(\".\").reduce((acc: any, part) => acc?.[part], entity);\n\n if (rawValue === undefined) return;\n const parts = fieldPath.split(\".\");\n const pathPlaceholders: string[] = [];\n\n parts.forEach((part, partIndex) => {\n const namePlaceholder = `#field${index}_${partIndex}`;\n pathPlaceholders.push(namePlaceholder);\n expressionAttributeNames[namePlaceholder] = part; // Mappt z.B. \"#field0_0\" auf \"loyalty\"\n });\n\n const fullPath = pathPlaceholders.join(\".\");\n const valuePlaceholder = `:val${index}`;\n\n updateExpressions.push(`${fullPath} = ${valuePlaceholder}`);\n\n const marshalledWrapper = marshall({ temp: rawValue }, { removeUndefinedValues: true });\n expressionAttributeValues[valuePlaceholder] = marshalledWrapper.temp;\n });\n\n if (updateExpressions.length === 0) return entity;\n\n const response = await this.dynamoDb.send(\n new UpdateItemCommand({\n TableName: this._tableName,\n Key: marshall({ [partitionKey]: entityId }),\n UpdateExpression: `SET ${updateExpressions.join(\", \")}`,\n ExpressionAttributeNames: expressionAttributeNames,\n ExpressionAttributeValues: expressionAttributeValues,\n ReturnValues: ReturnValue.ALL_NEW,\n }),\n );\n\n return response.Attributes ? (unmarshall(response.Attributes) as Partial<T>) : entity;\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 const selectedFields = Array.from(new Set([...(fieldNames || []), partitionKey]));\n const entityListCleaned = removeFields(entityList, selectedFields);\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(selectedFields)}`,\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, fieldPath: string[], delta: number): Promise<T> {\n const partitionKey = this._indexMap.partitionKey;\n const leafField = fieldPath[fieldPath.length - 1];\n\n if (!this?._indexMap?.numberFields?.includes(leafField)) {\n throw new Error(`${leafField} field not found in indexMap.numberFields`);\n }\n\n const expressionAttributeNames: Record<string, string> = {};\n fieldPath.forEach((segment, i) => {\n expressionAttributeNames[`#f${i}`] = segment;\n });\n\n const pathExpr = fieldPath.map((_, i) => `#f${i}`).join(\".\");\n\n const params: UpdateItemCommandInput = {\n TableName: this._tableName,\n Key: marshall({ [partitionKey]: entityId }),\n UpdateExpression: `SET ${pathExpr} = if_not_exists(${pathExpr}, :start) + :delta`,\n ExpressionAttributeNames: expressionAttributeNames,\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"]}
|
|
@@ -23,6 +23,7 @@ export declare abstract class CrudServiceImpl<T extends BaseEntity, D extends Ba
|
|
|
23
23
|
saveAll(entities: Partial<T>[], ownerId: string, parentId?: string, createdByUser?: string | CognitoUser, isTransactional?: boolean): Promise<Partial<T>[]>;
|
|
24
24
|
update(entity: Partial<T>, requestUser?: CognitoUser, fields?: string[]): Promise<T>;
|
|
25
25
|
updateAll(entities: Partial<T>[], fields: string[], requestUser?: CognitoUser, isTransactional?: boolean): Promise<boolean>;
|
|
26
|
+
updateFields(entity: Partial<T>, fields: string[], requestUser?: CognitoUser): Promise<Partial<T>>;
|
|
26
27
|
remove(entityId: string, requestUser?: CognitoUser): Promise<boolean>;
|
|
27
28
|
removeAll(entityIds: string[], requestUser?: CognitoUser): Promise<boolean>;
|
|
28
29
|
removeMatch(filter: Filter | string, requestUser?: CognitoUser): Promise<boolean>;
|
|
@@ -39,11 +39,17 @@ export interface CrudService<T extends BaseEntity> {
|
|
|
39
39
|
* Only the specified fields will be updated for each entity.
|
|
40
40
|
* @param requestUser - Cognito user, system if not exist
|
|
41
41
|
* @param entity - An array of entities with updated fields.
|
|
42
|
-
* @param fields - The list of field names to update in each entity.
|
|
42
|
+
* @param fields - The list of field names to update in each entity. Supports dot paths (e.g. `author.name`).
|
|
43
43
|
* @param isTransactional - Whether to perform the operation in a transaction.
|
|
44
44
|
* @returns True if all entities were successfully updated.
|
|
45
45
|
*/
|
|
46
46
|
updateAll(entity: T[], fields: string[], requestUser?: CognitoUser, isTransactional?: boolean): Promise<boolean>;
|
|
47
|
+
/**
|
|
48
|
+
* Updates selected fields for one entity. The entity object provides both the
|
|
49
|
+
* partition-key value (to identify the item) and the new field values to write.
|
|
50
|
+
* Supports dot paths (e.g. `author.name`).
|
|
51
|
+
*/
|
|
52
|
+
updateFields(entity: Partial<T>, fields: string[], requestUser?: CognitoUser): Promise<Partial<T>>;
|
|
47
53
|
/**
|
|
48
54
|
* Deletes an entity by ID for the given user.
|
|
49
55
|
* @param requestUser - Cognito user, system if not exist
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crud.service.interface.js","sourceRoot":"","sources":["../../src/service/crud.service.interface.ts"],"names":[],"mappings":"","sourcesContent":["import { BaseEntity, CognitoUser, 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 CrudService<T extends BaseEntity> {\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 parentId\n * @param createdByUser - The created user.\n * @returns The created entity.\n */\n save(entity: Partial<T>, ownerId: string, parentId?: string, createdByUser?: CognitoUser): 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 parentId\n * @param createdByUser - The created user.\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 parentId?: string,\n createdByUser?: CognitoUser,\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 requestUser - Cognito user, system if not exist\n * @param entity - The entity with updated fields.\n * @returns The updated entity.\n */\n update(entity: Partial<T>, requestUser?: CognitoUser, fields?: 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 requestUser - Cognito user, system if not exist\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[], requestUser?: CognitoUser, isTransactional?: boolean): Promise<boolean>;\n\n /**\n * Deletes an entity by ID for the given user.\n * @param requestUser - Cognito user, system if not exist\n * @param entityId - The ID of the entity to delete.\n * @returns True if the entity was successfully deleted.\n */\n remove(entityId: string, requestUser?: CognitoUser): Promise<boolean>;\n\n deleteFields(entityId: string, fields: string[]): Promise<Partial<T>>;\n\n /**\n * Deletes multiple entities by their IDs for the given user.\n * @param requestUser - Cognito user, system if not exist\n * @param entityIds - An array of entity IDs to delete.\n * @returns True if all entities were successfully deleted.\n */\n removeAll(entityIds: string[], requestUser?: CognitoUser): Promise<boolean>;\n\n removeMatch(filter: Filter | string, requestUser?: CognitoUser): Promise<boolean>;\n\n /**\n * Retrieves an entity by its ID for the given user.\n * @param requestUser - Cognito user, system if not exist\n * @param entityId - The ID of the entity to retrieve.\n * @returns The requested entity.\n */\n findById(entityId: string, requestUser?: CognitoUser): Promise<T>;\n\n /**\n * Retrieves multiple entities by their IDs for the given user.\n * @param requestUser - Cognito user, system if not exist\n * @param entityIds - An array of entity IDs to retrieve.\n * @returns An array of found entities.\n */\n findByIds(entityIds: string[], requestUser?: CognitoUser): 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 | string): 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(\n queryParams: any,\n debug?: boolean,\n ): Promise<{ items: Partial<T>[]; total: number; aggs?: Record<string, any> }>;\n\n searchQueryTotalCount(queryParams: any): Promise<number>;\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 throwErrorsHttp(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 | string): Promise<List<Partial<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 setIndexMapDB(indexMap: DynamoIndexMap): boolean;\n\n incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n\n decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"crud.service.interface.js","sourceRoot":"","sources":["../../src/service/crud.service.interface.ts"],"names":[],"mappings":"","sourcesContent":["import { BaseEntity, CognitoUser, 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 CrudService<T extends BaseEntity> {\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 parentId\n * @param createdByUser - The created user.\n * @returns The created entity.\n */\n save(entity: Partial<T>, ownerId: string, parentId?: string, createdByUser?: CognitoUser): 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 parentId\n * @param createdByUser - The created user.\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 parentId?: string,\n createdByUser?: CognitoUser,\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 requestUser - Cognito user, system if not exist\n * @param entity - The entity with updated fields.\n * @returns The updated entity.\n */\n update(entity: Partial<T>, requestUser?: CognitoUser, fields?: 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 requestUser - Cognito user, system if not exist\n * @param entity - An array of entities with updated fields.\n * @param fields - The list of field names to update in each entity. Supports dot paths (e.g. `author.name`).\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[], requestUser?: CognitoUser, isTransactional?: boolean): Promise<boolean>;\n\n /**\n * Updates selected fields for one entity. The entity object provides both the\n * partition-key value (to identify the item) and the new field values to write.\n * Supports dot paths (e.g. `author.name`).\n */\n updateFields(entity: Partial<T>, fields: string[], requestUser?: CognitoUser): Promise<Partial<T>>;\n\n /**\n * Deletes an entity by ID for the given user.\n * @param requestUser - Cognito user, system if not exist\n * @param entityId - The ID of the entity to delete.\n * @returns True if the entity was successfully deleted.\n */\n remove(entityId: string, requestUser?: CognitoUser): Promise<boolean>;\n\n deleteFields(entityId: string, fields: string[]): Promise<Partial<T>>;\n\n /**\n * Deletes multiple entities by their IDs for the given user.\n * @param requestUser - Cognito user, system if not exist\n * @param entityIds - An array of entity IDs to delete.\n * @returns True if all entities were successfully deleted.\n */\n removeAll(entityIds: string[], requestUser?: CognitoUser): Promise<boolean>;\n\n removeMatch(filter: Filter | string, requestUser?: CognitoUser): Promise<boolean>;\n\n /**\n * Retrieves an entity by its ID for the given user.\n * @param requestUser - Cognito user, system if not exist\n * @param entityId - The ID of the entity to retrieve.\n * @returns The requested entity.\n */\n findById(entityId: string, requestUser?: CognitoUser): Promise<T>;\n\n /**\n * Retrieves multiple entities by their IDs for the given user.\n * @param requestUser - Cognito user, system if not exist\n * @param entityIds - An array of entity IDs to retrieve.\n * @returns An array of found entities.\n */\n findByIds(entityIds: string[], requestUser?: CognitoUser): 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 | string): 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(\n queryParams: any,\n debug?: boolean,\n ): Promise<{ items: Partial<T>[]; total: number; aggs?: Record<string, any> }>;\n\n searchQueryTotalCount(queryParams: any): Promise<number>;\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 throwErrorsHttp(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 | string): Promise<List<Partial<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 setIndexMapDB(indexMap: DynamoIndexMap): boolean;\n\n incrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n\n decrementValueByField(entityId: string, fieldName: string, value?: number): Promise<T>;\n}\n"]}
|
|
@@ -105,6 +105,11 @@ class CrudServiceImpl {
|
|
|
105
105
|
log.warn("this methode is under development, cannot check ownership by updateAll");
|
|
106
106
|
return await this.repoDB.updateMany(entities, fields, isTransactional);
|
|
107
107
|
}
|
|
108
|
+
async updateFields(entity, fields, requestUser) {
|
|
109
|
+
if (!entity || !fields?.length)
|
|
110
|
+
return entity;
|
|
111
|
+
return this.repoDB.updateFields(entity, [...fields]);
|
|
112
|
+
}
|
|
108
113
|
async remove(entityId, requestUser) {
|
|
109
114
|
if (!entityId)
|
|
110
115
|
throw new Error("Entity id required");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crud.service.js","sourceRoot":"","sources":["../../src/service/crud.service.ts"],"names":[],"mappings":";;;;;;AAAA,oCAgBkB;AAClB,4CAAoF;AAIpF,kDAA0B;AAC1B,6EAA2E;AAE3E,MAAsB,eAAe;IAKzB,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,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,YAAY;QACV,OAAO,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC;IACpC,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,WAAmB;QACjC,MAAM,MAAM,GAAG,IAAA,wBAAgB,EAAC,WAAW,EAAE,IAAI,CAAC,aAAa,EAAE,CAAC,CAAC;QACnE,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC;QACjC,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAAgB,EAAE,MAAgB;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,OAAO,MAAW,CAAC;IACrB,CAAC;IAEO,UAAU,CAAC,OAAoC,EAAE,KAAoB;QAC3E,wCAAwC;QACxC,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACjD,OAAO,OAAO,IAAI,EAAE,CAAC;QACvB,CAAC;QAED,qCAAqC;QACrC,MAAM,UAAU,GAAG,CAAC,GAAG,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;QAExC,4DAA4D;QAC5D,MAAM,mBAAmB,GAAG,GAAG,CAAC;QAChC,IAAI,UAAU,CAAC,MAAM,IAAI,mBAAmB,EAAE,CAAC;YAC7C,UAAU,CAAC,KAAK,EAAE,CAAC,CAAC,gBAAgB;QACtC,CAAC;QAED,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACvB,OAAO,UAAU,CAAC;IACpB,CAAC;IAEO,aAAa,CAAC,MAAc,EAAE,MAAoB;QACxD,IAAI,CAAC,MAAM,CAAC,SAAS,IAAI,CAAC,MAAM,CAAC,UAAU;YAAE,OAAO,MAAM,CAAC;QAE3D,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,GAAG,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;AAziBD,0CAyiBC","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 removeFields,\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\";\nimport { buildSearchQueryOS } from \"../utils/opensearch/opensearch.parser\";\n\nexport abstract class CrudServiceImpl<\n T extends BaseEntity,\n D extends BaseRepoDB<T>,\n S extends BaseRepoES<T>,\n> implements CrudService<T> {\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 deleteFields(entityId: string, fields: string[]): Promise<Partial<T>> {\n return this.repoDB.deleteFields(entityId, fields);\n }\n\n async searchQuery(\n queryParams: any,\n debug?: boolean,\n ): Promise<{ items: Partial<T>[]; total: number; aggs?: Record<string, any> }> {\n const query = buildSearchQueryOS(queryParams, this.config);\n\n return await this.repoES.search(query, debug);\n }\n\n async searchQueryTotalCount(queryParams: any): Promise<number> {\n const query = buildSearchQueryOS(queryParams, this.config);\n\n return this.repoES.count(query);\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 | string): Promise<List<Partial<T>>> {\n if (typeof filter === \"string\") filter = parseIndexFilter(filter, this.getIndexMapDB());\n\n let parsedFilter = this.parseOwnerFields(filter, this.config);\n parsedFilter = this.setIndexField(parsedFilter, this.config);\n\n return this.repoES.find(parsedFilter);\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 // if (!entity.createdBy) 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: Partial<T>, requestUser?: CognitoUser, fields?: string[]): Promise<T> {\n const fieldName = this.config.DYNAMO_DB?.MAP?.partitionKey ?? \"id\";\n if (fields && fields.length > 0) fields.push(fieldName);\n if (fields && fields.length > 0) entity = removeFields([entity], fields)[0];\n\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.isScope &&\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 && 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 requestUser &&\n !requestUser.isScope &&\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 removeMatch(filter: Filter | string, requestUser?: CognitoUser): Promise<boolean> {\n const { items } = await this.find(filter);\n if (items.length === 0) return true;\n\n return this.removeAll(\n items.map((item) => item.id),\n requestUser,\n );\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 | string): Promise<T[]> {\n if (typeof filter === \"string\") filter = parseIndexFilter(filter, this.getIndexMapDB());\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 | string): Promise<List<Partial<T>>> {\n if (typeof filter === \"string\") filter = parseIndexFilter(filter, this.getIndexMapDB());\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 throwErrorsHttp(code: number, message: string, errorContent?: any): void {\n throw new ErrorHttp({ code, 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 !== \"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 !== \"profileId\") 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 !== \"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 undefined;\n\n if (typeof requestUser === \"string\") return requestUser;\n\n return requestUser.username;\n }\n\n private handleCreate(entity: Partial<T>, user: string, date: string): T {\n const dayjsData = dayjs(new Date(date));\n\n const noIdExist = entity[this.config.DYNAMO_DB.MAP.partitionKey ?? \"id\"] === undefined;\n if (noIdExist) entity[this.config.DYNAMO_DB.MAP.partitionKey ?? \"id\"] = crypto.randomUUID();\n\n entity.createdAt = date;\n if (user) entity.createdBy = user;\n entity.year = dayjsData.year().toString();\n entity.yearMonth = dayjsData.format(\"YYYY-MM\");\n\n if (!entity.updatedAt) {\n entity.updatedAt = entity.createdAt;\n }\n\n if (!this.config.TRACE_CHANGE?.fields) return entity as T;\n\n entity.history = this.addHistory(entity.history, { action: Action.CREATE, user, date });\n return entity as T;\n }\n\n private handleUpdate(entity: Partial<T>, itemOld: T | undefined, user: string, date: string): T {\n if (user) entity.updatedBy = user;\n entity.history = entity.history || itemOld?.history;\n\n entity.updatedAt = date;\n\n if (!this.config.TRACE_CHANGE?.fields || !itemOld) {\n return entity as T;\n }\n\n const changes = computeChangedFields(itemOld, entity, this.config.TRACE_CHANGE);\n if (changes.length > 0) {\n entity.history = this.addHistory(entity.history, {\n action: Action.UPDATE,\n user,\n date,\n changes,\n });\n }\n\n return entity 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,oCAgBkB;AAClB,4CAAoF;AAIpF,kDAA0B;AAC1B,6EAA2E;AAE3E,MAAsB,eAAe;IAKzB,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,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,YAAY;QACV,OAAO,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC;I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CAAC,UAAU;YAAE,OAAO,MAAM,CAAC;QAE3D,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,GAAG,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;AA9iBD,0CA8iBC","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 removeFields,\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\";\nimport { buildSearchQueryOS } from \"../utils/opensearch/opensearch.parser\";\n\nexport abstract class CrudServiceImpl<\n T extends BaseEntity,\n D extends BaseRepoDB<T>,\n S extends BaseRepoES<T>,\n> implements CrudService<T> {\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 deleteFields(entityId: string, fields: string[]): Promise<Partial<T>> {\n return this.repoDB.deleteFields(entityId, fields);\n }\n\n async searchQuery(\n queryParams: any,\n debug?: boolean,\n ): Promise<{ items: Partial<T>[]; total: number; aggs?: Record<string, any> }> {\n const query = buildSearchQueryOS(queryParams, this.config);\n\n return await this.repoES.search(query, debug);\n }\n\n async searchQueryTotalCount(queryParams: any): Promise<number> {\n const query = buildSearchQueryOS(queryParams, this.config);\n\n return this.repoES.count(query);\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 | string): Promise<List<Partial<T>>> {\n if (typeof filter === \"string\") filter = parseIndexFilter(filter, this.getIndexMapDB());\n\n let parsedFilter = this.parseOwnerFields(filter, this.config);\n parsedFilter = this.setIndexField(parsedFilter, this.config);\n\n return this.repoES.find(parsedFilter);\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 // if (!entity.createdBy) 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: Partial<T>, requestUser?: CognitoUser, fields?: string[]): Promise<T> {\n const fieldName = this.config.DYNAMO_DB?.MAP?.partitionKey ?? \"id\";\n if (fields && fields.length > 0) fields.push(fieldName);\n if (fields && fields.length > 0) entity = removeFields([entity], fields)[0];\n\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.isScope &&\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 updateFields(entity: Partial<T>, fields: string[], requestUser?: CognitoUser): Promise<Partial<T>> {\n if (!entity || !fields?.length) return entity;\n return this.repoDB.updateFields(entity, [...fields]);\n }\n\n async remove(entityId: string, requestUser?: CognitoUser): Promise<boolean> {\n if (!entityId) throw new Error(\"Entity id required\");\n\n if (requestUser && 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 requestUser &&\n !requestUser.isScope &&\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 removeMatch(filter: Filter | string, requestUser?: CognitoUser): Promise<boolean> {\n const { items } = await this.find(filter);\n if (items.length === 0) return true;\n\n return this.removeAll(\n items.map((item) => item.id),\n requestUser,\n );\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 | string): Promise<T[]> {\n if (typeof filter === \"string\") filter = parseIndexFilter(filter, this.getIndexMapDB());\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 | string): Promise<List<Partial<T>>> {\n if (typeof filter === \"string\") filter = parseIndexFilter(filter, this.getIndexMapDB());\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 throwErrorsHttp(code: number, message: string, errorContent?: any): void {\n throw new ErrorHttp({ code, 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 !== \"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 !== \"profileId\") 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 !== \"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 undefined;\n\n if (typeof requestUser === \"string\") return requestUser;\n\n return requestUser.username;\n }\n\n private handleCreate(entity: Partial<T>, user: string, date: string): T {\n const dayjsData = dayjs(new Date(date));\n\n const noIdExist = entity[this.config.DYNAMO_DB.MAP.partitionKey ?? \"id\"] === undefined;\n if (noIdExist) entity[this.config.DYNAMO_DB.MAP.partitionKey ?? \"id\"] = crypto.randomUUID();\n\n entity.createdAt = date;\n if (user) entity.createdBy = user;\n entity.year = dayjsData.year().toString();\n entity.yearMonth = dayjsData.format(\"YYYY-MM\");\n\n if (!entity.updatedAt) {\n entity.updatedAt = entity.createdAt;\n }\n\n if (!this.config.TRACE_CHANGE?.fields) return entity as T;\n\n entity.history = this.addHistory(entity.history, { action: Action.CREATE, user, date });\n return entity as T;\n }\n\n private handleUpdate(entity: Partial<T>, itemOld: T | undefined, user: string, date: string): T {\n if (user) entity.updatedBy = user;\n entity.history = entity.history || itemOld?.history;\n\n entity.updatedAt = date;\n\n if (!this.config.TRACE_CHANGE?.fields || !itemOld) {\n return entity as T;\n }\n\n const changes = computeChangedFields(itemOld, entity, this.config.TRACE_CHANGE);\n if (changes.length > 0) {\n entity.history = this.addHistory(entity.history, {\n action: Action.UPDATE,\n user,\n date,\n changes,\n });\n }\n\n return entity 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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aws-service-stack",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.406",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"author": "chinggis.systems",
|
|
@@ -13,7 +13,11 @@
|
|
|
13
13
|
"registry": "https://registry.npmjs.org/",
|
|
14
14
|
"access": "public"
|
|
15
15
|
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=20"
|
|
18
|
+
},
|
|
16
19
|
"scripts": {
|
|
20
|
+
"check": "tsc --noEmit",
|
|
17
21
|
"test": "jest",
|
|
18
22
|
"build": "tsc && tsc-alias",
|
|
19
23
|
"release": "npm version patch --no-git-tag && npm run build"
|
|
@@ -49,10 +53,10 @@
|
|
|
49
53
|
"devDependencies": {
|
|
50
54
|
"@types/aws-lambda": "^8.10.161",
|
|
51
55
|
"@types/jest": "^30.0.0",
|
|
52
|
-
"eslint": "^10.0
|
|
53
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
54
|
-
"@typescript-eslint/parser": "^8.
|
|
55
|
-
"jest": "^30.
|
|
56
|
+
"eslint": "^10.1.0",
|
|
57
|
+
"@typescript-eslint/eslint-plugin": "^8.58.0",
|
|
58
|
+
"@typescript-eslint/parser": "^8.58.0",
|
|
59
|
+
"jest": "^30.3.0",
|
|
56
60
|
"jest-transform-stub": "^2.0.0",
|
|
57
61
|
"jsonc-eslint-parser": "^3.1.0",
|
|
58
62
|
"serverless-offline": "^14.5.0",
|
|
@@ -60,7 +64,7 @@
|
|
|
60
64
|
"ts-jest": "^29.4.6",
|
|
61
65
|
"ts-node": "^10.9.2",
|
|
62
66
|
"tsc-alias": "^1.8.16",
|
|
63
|
-
"typescript": "^
|
|
67
|
+
"typescript": "^6.0.2",
|
|
64
68
|
"prettier": "^3.8.1",
|
|
65
69
|
"typescript-transform-paths": "^3.5.6"
|
|
66
70
|
}
|