aws-service-stack 0.17.288 → 0.18.290

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.
@@ -103,7 +103,7 @@ let CommissionServiceImpl = class CommissionServiceImpl extends service_1.CrudSe
103
103
  const fee = percentList
104
104
  .filter((item) => item.retailerUsername === retailerRegNum)
105
105
  .map((item) => item.toRetailerPercent)[0];
106
- return !fee ? 0 : fee;
106
+ return fee || 0;
107
107
  }
108
108
  };
109
109
  exports.CommissionServiceImpl = CommissionServiceImpl;
@@ -1 +1 @@
1
- {"version":3,"file":"commission-service.js","sourceRoot":"","sources":["../../../../src/_examples/service/commission/commission-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAA8C;AAC9C,uEAAuD;AACvD,kDAA0B;AAC1B,iDAA4C;AAG5C,oEAAkE;AAGlE,6CAA2C;AAG3C,wCAAsC;AAGtC,8EAAqF;AAK9E,IAAM,qBAAqB,GAA3B,MAAM,qBACX,SAAQ,yBAAmD;IAG1C,OAAO,CAAsB;IAC7B,eAAe,CAAkB;IACjC,eAAe,CAAkB;IAElD;QACE,MAAM,MAAM,GAAqB,gBAAS,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;QACnE,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;QAEzC,IAAI,CAAC,eAAe,GAAG,gBAAS,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;QAC5D,IAAI,CAAC,eAAe,GAAG,gBAAS,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,gBAAwB,EAAE,gBAAwB,EAAE,iBAA0B;QACzF,MAAM,QAAQ,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,EAAE,QAAQ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AAC;SACrD,EACD,gBAAgB,CACjB,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,+BAA+B,CAAC,cAAsB,EAAE,cAAsB;QAClF,IAAI,CAAC,cAAc,IAAI,CAAC,cAAc,EAAE,CAAC;YACvC,OAAO,CAAC,KAAK,CAAC,6CAA6C,CAAC,CAAC;YAC7D,OAAO,CAAC,CAAC;QACX,CAAC;QAED,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QAEzE,MAAM,GAAG,GAAG,WAAW;aACpB,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,gBAAgB,KAAK,cAAc,CAAC;aAC1D,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;QAE5C,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACxB,CAAC;CACF,CAAA;AAxEY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,gBAAO,EAAC,mBAAmB,CAAC;;GAChB,qBAAqB,CAwEjC","sourcesContent":["import { CrudServiceImpl } from \"src/service\";\nimport { HTTP } from \"src/exception/exception-handler\";\nimport dayjs from \"dayjs\";\nimport Container, { Service } from \"typedi\";\n\nimport { CommissionRepoDB } from \"src/_examples/repositories/commission/commission-repo-db.interface\";\nimport \"src/_examples/repositories/commission/commission-repo-db\";\n\nimport { SupplierService } from \"../supplier/supplier-service-crud.interface\";\nimport \"../supplier/supplier-service-crud\";\n\nimport { RAccountService } from \"../raccount/raccount-service.interface\";\nimport \"../raccount/raccount-service\";\n\nimport { Commission } from \"src/_examples/model-shared/commission.model\";\nimport { ContractStatus, Retailer } from \"src/_examples/model-shared/raccount.model\";\n\nimport { CommissionService } from \"./commission-service.interface\";\n\n@Service(\"CommissionService\")\nexport class CommissionServiceImpl\n extends CrudServiceImpl<Commission, CommissionRepoDB, null>\n implements CommissionService\n{\n private readonly feePool: Map<string, number>;\n private readonly supplierService: SupplierService;\n private readonly rAccountService: RAccountService;\n\n constructor() {\n const repoDB: CommissionRepoDB = Container.get(\"CommissionRepoDB\");\n super(repoDB, null);\n this.feePool = new Map<string, number>();\n\n this.supplierService = Container.get(\"SupplierCrudService\");\n this.rAccountService = Container.get(\"RAccountService\");\n }\n\n async create(supplierUsername: string, retailerUsername: string, toRetailerPercent?: number): Promise<Commission> {\n const supplier = (await this.supplierService.find({ username: supplierUsername })).items[0];\n const retailer = (await this.rAccountService.find({ username: retailerUsername })).items[0];\n\n if (retailer.contractStatus === ContractStatus.EXPIRED) {\n this.throwError(HTTP.BAD_REQUEST.code, \"Уг retailer идэвхжээгүй байна.\");\n }\n\n const existingFee = await this.find({\n supplierUsername,\n retailerUsername,\n });\n\n if (existingFee.items.length > 0) {\n this.throwError(\n HTTP.BAD_REQUEST.code,\n `Fee already exist on supplier: ${supplierUsername} and retailer: ${retailerUsername}`,\n );\n return;\n }\n\n const percentage = retailer.commission1 ?? retailer.commission2;\n\n return this.save(\n {\n supplierUsername: supplierUsername,\n retailerUsername: retailerUsername,\n toRetailerPercent: toRetailerPercent ?? percentage,\n supplier: {\n firstName: supplier.firstName + \" \" + supplier.lastName,\n username: supplier.username,\n taxPayer: supplier.taxPayer,\n },\n retailer: retailer as Retailer,\n isActive: true,\n createdMonth: dayjs(new Date()).format(\"YYYY-MM-DD\"),\n },\n retailerUsername,\n );\n }\n\n async getRetailerCommissionBySupplier(retailerRegNum: string, supplierRegNum: string): Promise<number> {\n if (!retailerRegNum || !supplierRegNum) {\n console.error(\"retailerRegNum or supplierRegNum is missing\");\n return 0;\n }\n\n const percentList = await this.findAllByIndex(\"byOwner\", supplierRegNum);\n\n const fee = percentList\n .filter((item) => item.retailerUsername === retailerRegNum)\n .map((item) => item.toRetailerPercent)[0];\n\n return !fee ? 0 : fee;\n }\n}\n"]}
1
+ {"version":3,"file":"commission-service.js","sour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,EAAE,EAAE,CAAC,IAAI,CAAC,gBAAgB,KAAK,cAAc,CAAC;aAC1D,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;QAE5C,OAAO,GAAG,IAAI,CAAC,CAAC;IAClB,CAAC;CACF,CAAA;AAxEY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,gBAAO,EAAC,mBAAmB,CAAC;;GAChB,qBAAqB,CAwEjC","sourcesContent":["import { CrudServiceImpl } from \"src/service\";\nimport { HTTP } from \"src/exception/exception-handler\";\nimport dayjs from \"dayjs\";\nimport Container, { Service } from \"typedi\";\n\nimport { CommissionRepoDB } from \"src/_examples/repositories/commission/commission-repo-db.interface\";\nimport \"src/_examples/repositories/commission/commission-repo-db\";\n\nimport { SupplierService } from \"../supplier/supplier-service-crud.interface\";\nimport \"../supplier/supplier-service-crud\";\n\nimport { RAccountService } from \"../raccount/raccount-service.interface\";\nimport \"../raccount/raccount-service\";\n\nimport { Commission } from \"src/_examples/model-shared/commission.model\";\nimport { ContractStatus, Retailer } from \"src/_examples/model-shared/raccount.model\";\n\nimport { CommissionService } from \"./commission-service.interface\";\n\n@Service(\"CommissionService\")\nexport class CommissionServiceImpl\n extends CrudServiceImpl<Commission, CommissionRepoDB, null>\n implements CommissionService\n{\n private readonly feePool: Map<string, number>;\n private readonly supplierService: SupplierService;\n private readonly rAccountService: RAccountService;\n\n constructor() {\n const repoDB: CommissionRepoDB = Container.get(\"CommissionRepoDB\");\n super(repoDB, null);\n this.feePool = new Map<string, number>();\n\n this.supplierService = Container.get(\"SupplierCrudService\");\n this.rAccountService = Container.get(\"RAccountService\");\n }\n\n async create(supplierUsername: string, retailerUsername: string, toRetailerPercent?: number): Promise<Commission> {\n const supplier = (await this.supplierService.find({ username: supplierUsername })).items[0];\n const retailer = (await this.rAccountService.find({ username: retailerUsername })).items[0];\n\n if (retailer.contractStatus === ContractStatus.EXPIRED) {\n this.throwError(HTTP.BAD_REQUEST.code, \"Уг retailer идэвхжээгүй байна.\");\n }\n\n const existingFee = await this.find({\n supplierUsername,\n retailerUsername,\n });\n\n if (existingFee.items.length > 0) {\n this.throwError(\n HTTP.BAD_REQUEST.code,\n `Fee already exist on supplier: ${supplierUsername} and retailer: ${retailerUsername}`,\n );\n return;\n }\n\n const percentage = retailer.commission1 ?? retailer.commission2;\n\n return this.save(\n {\n supplierUsername: supplierUsername,\n retailerUsername: retailerUsername,\n toRetailerPercent: toRetailerPercent ?? percentage,\n supplier: {\n firstName: supplier.firstName + \" \" + supplier.lastName,\n username: supplier.username,\n taxPayer: supplier.taxPayer,\n },\n retailer: retailer as Retailer,\n isActive: true,\n createdMonth: dayjs(new Date()).format(\"YYYY-MM-DD\"),\n },\n retailerUsername,\n );\n }\n\n async getRetailerCommissionBySupplier(retailerRegNum: string, supplierRegNum: string): Promise<number> {\n if (!retailerRegNum || !supplierRegNum) {\n console.error(\"retailerRegNum or supplierRegNum is missing\");\n return 0;\n }\n\n const percentList = await this.findAllByIndex(\"byOwner\", supplierRegNum);\n\n const fee = percentList\n .filter((item) => item.retailerUsername === retailerRegNum)\n .map((item) => item.toRetailerPercent)[0];\n\n return fee || 0;\n }\n}\n"]}
@@ -20,11 +20,11 @@ let ProfileServiceImpl = class ProfileServiceImpl extends core_1.CrudServiceImpl
20
20
  super(typedi_1.Container.get("ProfileRepoDB"), null);
21
21
  }
22
22
  async deletePhone(profileId) {
23
+ const profile = await this.findById(profileId);
24
+ if (!profile.phone) {
25
+ throw new errors_1.ErrorHttp({ code: 400, error: "Уг хаяг дээр утасны дугаар байхгүй байна!" });
26
+ }
23
27
  try {
24
- const profile = await this.findById("system", profileId);
25
- if (!profile.phone) {
26
- throw new errors_1.ErrorHttp({ code: 400, error: "Уг хаяг дээр утасны дугаар байхгүй байна!" });
27
- }
28
28
  if (profile.oldPhoneNumbers) {
29
29
  profile.oldPhoneNumbers.push(profile.phone);
30
30
  }
@@ -46,7 +46,7 @@ let ProfileServiceImpl = class ProfileServiceImpl extends core_1.CrudServiceImpl
46
46
  if (!profileSource || !profileTarget) {
47
47
  throw new errors_1.ErrorHttp({
48
48
  code: 400,
49
- error: `Тухайн ID дээр профайл олдсонгүй: ${!profileSource ? profileIdSource : profileIdTarget}`,
49
+ error: `Тухайн ID дээр профайл олдсонгүй: ${profileSource ? profileIdTarget : profileIdSource}`,
50
50
  });
51
51
  }
52
52
  try {
@@ -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,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;YACzD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;gBACnB,MAAM,IAAI,kBAAS,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,2CAA2C,EAAE,CAAC,CAAC;YACzF,CAAC;YAED,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,qBA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M,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;CACF,CAAA;AAzIY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,gBAAO,EAAC,gBAAgB,CAAC;;GACb,kBAAkB,CAyI9B","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 try {\n const profile = await this.findById(\"system\", profileId);\n if (!profile.phone) {\n throw new ErrorHttp({ code: 400, error: \"Уг хаяг дээр утасны дугаар байхгүй байна!\" });\n }\n\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, \"system\");\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 ? profileIdSource : profileIdTarget}`,\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], \"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,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,SA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AAC;QACvE,IAAI,OAAO,CAAC,WAAW,IAAI,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 { 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, \"system\");\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], \"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"]}
@@ -59,7 +59,7 @@ let SupplierCrudServiceImpl = class SupplierCrudServiceImpl extends crud_service
59
59
  super(repoDB, repoES);
60
60
  }
61
61
  async convertToCognitoUser(username, email) {
62
- const supplier = await this.findById("system", username);
62
+ const supplier = await this.findById(username);
63
63
  if (!supplier)
64
64
  return this.throwError(core_1.HTTP.BAD_REQUEST.code, "supplier not found!");
65
65
  if (supplier?.loginStatus === "pending")
@@ -1 +1 @@
1
- {"version":3,"file":"supplier-service-crud.js","sourceRoot":"","sources":["../../../../src/_examples/service/supplier/supplier-service-crud.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAA4C;AAK5C,wDAAsD;AAGtD,wDAAsD;AACtD,yCAAuF;AAEvF,+EAAgF;AAChF,gEAAgE;AAGzD,IAAM,uBAAuB,GAA7B,MAAM,uBACX,SAAQ,8BAAyD;IAGjE,mFAAmF;IACnF,0EAA0E;IAE1E,EAAE;IACF;QACE,MAAM,MAAM,GAAmB,gBAAS,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAC/D,MAAM,MAAM,GAAmB,gBAAS,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAC/D,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxB,CAAC;IAED,KAAK,CAAC,oBAAoB,CAAC,QAAgB,EAAE,KAAa;QACxD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QAEzD,IAAI,CAAC,QAAQ;YAAE,OAAO,IAAI,CAAC,UAAU,CAAC,WAAI,CAAC,WAAW,CAAC,IAAI,EAAE,qBAAqB,CAAC,CAAC;QACpF,IAAI,QAAQ,EAAE,WAAW,KAAK,SAAS;YAAE,OAAO,IAAI,CAAC,UAAU,CAA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B,uBAAuB,CAkGnC","sourcesContent":["import Container, { Service } from \"typedi\";\n\nimport { SupplierService } from \"./supplier-service-crud.interface\";\n\nimport { SupplierRepoDB } from \"../../repositories/supplier/supplier-repo-db.interface\";\nimport \"../../repositories/supplier/supplier-repo-db\";\n\nimport { SupplierRepoES } from \"../../repositories/supplier/supplier-repo-es.interface\";\nimport \"../../repositories/supplier/supplier-repo-es\";\nimport { ActionDynamoDB, Filter, HTTP, List, toCaseInsensitive } from \"@chinggis/core\";\nimport { SAccount } from \"../../model-shared/suppler.model-to-remove\";\nimport { openSearch_supplier } from \"../../controller/supplier/supplier-config\";\nimport { CrudServiceImpl } from \"../../../service/crud.service\";\n\n@Service(\"SupplierCrudService\")\nexport class SupplierCrudServiceImpl\n extends CrudServiceImpl<SAccount, SupplierRepoDB, SupplierRepoES>\n implements SupplierService\n{\n // @Inject(\"EcomOrderService\") private readonly ecomOrderService: EcomOrderService;\n // @Inject(\"ROrderService\") private readonly rOrderService: ROrderService;\n\n //\n constructor() {\n const repoDB: SupplierRepoDB = Container.get(\"SupplierRepoDB\");\n const repoES: SupplierRepoES = Container.get(\"SupplierRepoES\");\n super(repoDB, repoES);\n }\n\n async convertToCognitoUser(username: string, email: string): Promise<void> {\n const supplier = await this.findById(\"system\", username);\n\n if (!supplier) return this.throwError(HTTP.BAD_REQUEST.code, \"supplier not found!\");\n if (supplier?.loginStatus === \"pending\") return this.throwError(HTTP.BAD_REQUEST.code, \"already pending user!\");\n if (supplier?.loginStatus === \"confirmed\") return this.throwError(HTTP.BAD_REQUEST.code, \"already confirmed user!\");\n }\n\n async ListNonLevelOne(filterAndSort: Filter): Promise<List<SAccount>> {\n if (filterAndSort.page > 0) filterAndSort.page = filterAndSort.page - 1;\n const filter = {\n index: openSearch_supplier.index,\n body: {\n query: {\n bool: {\n must_not: [\n {\n term: {\n accountType: \"level1\",\n },\n },\n ],\n should: [],\n minimum_should_match: 1,\n },\n },\n from: filterAndSort.page * filterAndSort.size,\n size: filterAndSort.size,\n },\n };\n\n if (filterAndSort.page && filterAndSort.size) {\n filter.body.from = filterAndSort.page * filterAndSort.size;\n }\n\n if (filterAndSort.size) {\n filter.body.size = filterAndSort.size;\n }\n\n if (!filterAndSort.searchKeyword) {\n const result = await this.repoES.search(filter, true);\n return {\n items: result,\n lastKey: null,\n };\n }\n\n let searchKeyword = filterAndSort.searchKeyword.trim();\n\n const searchFields = [\"username\", \"firstName\", \"lastName\", \"phoneList\", \"bankAccountNumber\", \"bankName\"];\n searchKeyword = toCaseInsensitive(searchKeyword);\n searchFields.forEach((field) => {\n filter.body.query.bool.should.push({\n regexp: {\n [field]: {\n value: `.*${searchKeyword}.*`,\n case_insensitive: true,\n },\n },\n });\n });\n\n if (searchKeyword.includes(\"@\")) {\n filter.body.query.bool.should.push({\n wildcard: {\n \"email.keyword\": {\n value: `*${searchKeyword}*`,\n case_insensitive: true,\n },\n },\n });\n }\n\n const result = await this.repoES.search(filter);\n\n return {\n items: result,\n lastKey: null,\n };\n }\n\n async processChanges(itemOld: SAccount, itemNew: SAccount, action: ActionDynamoDB, tableName: string): Promise<any> {\n throw new Error(\"Method not implemented.\");\n }\n}\n"]}
1
+ {"version":3,"file":"supplier-service-crud.js","sourceRoot":"","sources":["../../../../src/_examples/service/supplier/supplier-service-crud.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAA4C;AAK5C,wDAAsD;AAGtD,wDAAsD;AACtD,yCAAuF;AAEvF,+EAAgF;AAChF,gEAAgE;AAGzD,IAAM,uBAAuB,GAA7B,MAAM,uBACX,SAAQ,8BAAyD;IAGjE,mFAAmF;IACnF,0EAA0E;IAE1E,EAAE;IACF;QACE,MAAM,MAAM,GAAmB,gBAAS,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAC/D,MAAM,MAAM,GAAmB,gBAAS,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAC/D,KAAK,CAAC,MAAM,EAA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AC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAEhD,OAAO;YACL,KAAK,EAAE,MAAM;YACb,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,OAAiB,EAAE,OAAiB,EAAE,MAAsB,EAAE,SAAiB;QAClG,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;CACF,CAAA;AAlGY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,gBAAO,EAAC,qBAAqB,CAAC;;GAClB,uBAAuB,CAkGnC","sourcesContent":["import Container, { Service } from \"typedi\";\n\nimport { SupplierService } from \"./supplier-service-crud.interface\";\n\nimport { SupplierRepoDB } from \"../../repositories/supplier/supplier-repo-db.interface\";\nimport \"../../repositories/supplier/supplier-repo-db\";\n\nimport { SupplierRepoES } from \"../../repositories/supplier/supplier-repo-es.interface\";\nimport \"../../repositories/supplier/supplier-repo-es\";\nimport { ActionDynamoDB, Filter, HTTP, List, toCaseInsensitive } from \"@chinggis/core\";\nimport { SAccount } from \"../../model-shared/suppler.model-to-remove\";\nimport { openSearch_supplier } from \"../../controller/supplier/supplier-config\";\nimport { CrudServiceImpl } from \"../../../service/crud.service\";\n\n@Service(\"SupplierCrudService\")\nexport class SupplierCrudServiceImpl\n extends CrudServiceImpl<SAccount, SupplierRepoDB, SupplierRepoES>\n implements SupplierService\n{\n // @Inject(\"EcomOrderService\") private readonly ecomOrderService: EcomOrderService;\n // @Inject(\"ROrderService\") private readonly rOrderService: ROrderService;\n\n //\n constructor() {\n const repoDB: SupplierRepoDB = Container.get(\"SupplierRepoDB\");\n const repoES: SupplierRepoES = Container.get(\"SupplierRepoES\");\n super(repoDB, repoES);\n }\n\n async convertToCognitoUser(username: string, email: string): Promise<void> {\n const supplier = await this.findById(username);\n\n if (!supplier) return this.throwError(HTTP.BAD_REQUEST.code, \"supplier not found!\");\n if (supplier?.loginStatus === \"pending\") return this.throwError(HTTP.BAD_REQUEST.code, \"already pending user!\");\n if (supplier?.loginStatus === \"confirmed\") return this.throwError(HTTP.BAD_REQUEST.code, \"already confirmed user!\");\n }\n\n async ListNonLevelOne(filterAndSort: Filter): Promise<List<SAccount>> {\n if (filterAndSort.page > 0) filterAndSort.page = filterAndSort.page - 1;\n const filter = {\n index: openSearch_supplier.index,\n body: {\n query: {\n bool: {\n must_not: [\n {\n term: {\n accountType: \"level1\",\n },\n },\n ],\n should: [],\n minimum_should_match: 1,\n },\n },\n from: filterAndSort.page * filterAndSort.size,\n size: filterAndSort.size,\n },\n };\n\n if (filterAndSort.page && filterAndSort.size) {\n filter.body.from = filterAndSort.page * filterAndSort.size;\n }\n\n if (filterAndSort.size) {\n filter.body.size = filterAndSort.size;\n }\n\n if (!filterAndSort.searchKeyword) {\n const result = await this.repoES.search(filter, true);\n return {\n items: result,\n lastKey: null,\n };\n }\n\n let searchKeyword = filterAndSort.searchKeyword.trim();\n\n const searchFields = [\"username\", \"firstName\", \"lastName\", \"phoneList\", \"bankAccountNumber\", \"bankName\"];\n searchKeyword = toCaseInsensitive(searchKeyword);\n searchFields.forEach((field) => {\n filter.body.query.bool.should.push({\n regexp: {\n [field]: {\n value: `.*${searchKeyword}.*`,\n case_insensitive: true,\n },\n },\n });\n });\n\n if (searchKeyword.includes(\"@\")) {\n filter.body.query.bool.should.push({\n wildcard: {\n \"email.keyword\": {\n value: `*${searchKeyword}*`,\n case_insensitive: true,\n },\n },\n });\n }\n\n const result = await this.repoES.search(filter);\n\n return {\n items: result,\n lastKey: null,\n };\n }\n\n async processChanges(itemOld: SAccount, itemNew: SAccount, action: ActionDynamoDB, tableName: string): Promise<any> {\n throw new Error(\"Method not implemented.\");\n }\n}\n"]}
@@ -12,11 +12,11 @@ export declare abstract class ControllerApi<R extends BaseEntity, T extends Crud
12
12
  processCrudRequestPre(req: HttpRequest): Promise<HttpRequest>;
13
13
  processCrudRequestPost(request: HttpRequest, response: R | List<R>): Promise<R | List<R>>;
14
14
  protected handleList(methode: HttpMethod, path: string, filter: Filter): Promise<any>;
15
- protected handleUpdate(entityId: string, requestBody: any, profileId?: string): Promise<R>;
16
- protected handleDelete(entityId: string, profileId?: string): Promise<boolean>;
17
- protected handleFetch(entityId: string, profileId?: string): Promise<R>;
18
- protected handleReplace(entityId: string, entity: any, profileId?: string): Promise<R>;
19
- protected handlePostCreate(entity: R, isAdmin: boolean, cognitoUser: CognitoUser): Promise<R>;
15
+ protected handleUpdate(entityId: string, requestBody: any, requestedUser?: CognitoUser): Promise<R>;
16
+ protected handleDelete(entityId: string, requestedUser?: CognitoUser): Promise<boolean>;
17
+ protected handleFetch(entityId: string, requestedUser?: CognitoUser): Promise<R>;
18
+ protected handleReplace(entityId: string, entity: any, requestedUser?: CognitoUser): Promise<R>;
19
+ protected handlePostCreate(entity: R, cognitoUser: CognitoUser): Promise<R>;
20
20
  protected abstract processCrudRequest(event: HttpRequest): Promise<any>;
21
21
  protected isListRequest(methode: HttpMethod, path: string): boolean;
22
22
  protected isUpdateRequest(methode: HttpMethod, path: string): boolean;
@@ -24,9 +24,9 @@ class ControllerApi {
24
24
  const policy = (0, index_1.findMatchedPolicy)(req.methode, event?.requestContext?.resourcePath, this.config.ENDPOINT_POLICY);
25
25
  this.checkPermission(policy?.access, req.requestType);
26
26
  this.validateRequest(policy?.validator, req.body);
27
- log.debug("groups: " + JSON.stringify(req.groups, null, 2));
27
+ log.debug("groups: " + JSON.stringify(req.identity.groups, null, 2));
28
28
  log.debug(`claims:${JSON.stringify(req.identity, null, 2)}`);
29
- log.debug(`groups:${req.groups}, isAdmin:${req.isAdmin}, userId:${req.userId}, profileId:${req.profileId}, username:${req.username}, requestType:${req.requestType}`);
29
+ log.debug(`groups:${req.identity.groups}, isAdmin:${req.identity.isAdmin}, userId:${req.identity.sub}, profileId:${req.identity.profile}, username:${req.identity.username}, requestType:${req.requestType}`);
30
30
  // if (req.isAdmin) {
31
31
  // delete req.filter["profileId"];
32
32
  // delete req.filter["ownerParentId"];
@@ -70,7 +70,7 @@ class ControllerApi {
70
70
  return await this.service.scan(filter || {});
71
71
  }
72
72
  }
73
- async handleUpdate(entityId, requestBody, profileId) {
73
+ async handleUpdate(entityId, requestBody, requestedUser) {
74
74
  if (!entityId)
75
75
  throw new exception_1.ErrorHttp({ code: 400, error: "BadRequest" }, "[CORE] Cannot PATCH resource without id field");
76
76
  const entity = this.parseEntity(requestBody);
@@ -83,22 +83,22 @@ class ControllerApi {
83
83
  throw new exception_1.ErrorHttp({ code: 400, error: "BadRequest" }, "[CORE] Cannot modify the id field");
84
84
  }
85
85
  entity[fieldName] = entityId;
86
- return this.service.update(entity, profileId);
86
+ return this.service.update(entity, requestedUser);
87
87
  }
88
- async handleDelete(entityId, profileId) {
88
+ async handleDelete(entityId, requestedUser) {
89
89
  if (!entityId)
90
90
  throw new exception_1.ErrorHttp({ code: 400, error: "BadRequest" }, "[CORE] Cannot delete resource without id field");
91
- return this.service.remove(entityId, profileId);
91
+ return this.service.remove(entityId, requestedUser);
92
92
  }
93
- async handleFetch(entityId, profileId) {
93
+ async handleFetch(entityId, requestedUser) {
94
94
  if (!entityId)
95
95
  throw new exception_1.ErrorHttp({ code: 400, error: "BadRequest" }, "[CORE] Cannot fetch resource without id field");
96
- const result = await this.service.findById(entityId, profileId);
96
+ const result = await this.service.findById(entityId, requestedUser);
97
97
  if (result)
98
98
  return result;
99
99
  throw new exception_1.ErrorHttp({ code: 404, error: "NotFound" }, `[CORE] Resource with ID ${entityId} not found`);
100
100
  }
101
- async handleReplace(entityId, entity, profileId) {
101
+ async handleReplace(entityId, entity, requestedUser) {
102
102
  if (!entityId)
103
103
  throw new exception_1.ErrorHttp({ code: 400, error: "BadRequest" }, "[CORE] Cannot PUT resource without id field");
104
104
  if (!Object.keys(entity).length) {
@@ -108,9 +108,9 @@ class ControllerApi {
108
108
  throw new exception_1.ErrorHttp({ code: 400, error: "BadRequest" }, "[CORE] Cannot PUT resource without id field");
109
109
  }
110
110
  entity.id = entityId;
111
- return this.service.update(entity, profileId);
111
+ return this.service.update(entity, requestedUser);
112
112
  }
113
- async handlePostCreate(entity, isAdmin, cognitoUser) {
113
+ async handlePostCreate(entity, cognitoUser) {
114
114
  if (!entity || Object.keys(entity).length === 0) {
115
115
  throw new exception_1.ErrorHttp({ code: 400, error: "BadRequest" }, "[CORE] No entity payload provided");
116
116
  }
@@ -122,7 +122,7 @@ class ControllerApi {
122
122
  let profileId = ownerId;
123
123
  let parentId;
124
124
  // Determine parentId and profileId
125
- if (isAdmin && inputParentId) {
125
+ if (cognitoUser.isAdmin && inputParentId) {
126
126
  parentId = inputParentId;
127
127
  }
128
128
  else if (cognitoUser.isParent) {
@@ -182,15 +182,15 @@ class ControllerApi {
182
182
  const path = req.event?.requestContext?.resourcePath;
183
183
  const entity = this.parseEntity(req.body);
184
184
  if (this.isUpdateRequest(req.methode, path))
185
- return this.handleUpdate(req.entityId, entity, req.profileId);
185
+ return this.handleUpdate(req.entityId, entity, req.identity);
186
186
  if (this.isDeleteRequest(req.methode, path))
187
- return this.handleDelete(req.entityId, req.profileId);
187
+ return this.handleDelete(req.entityId, req.identity);
188
188
  if (this.isFetchRequest(req.methode, path))
189
- return this.handleFetch(req.entityId, req.profileId);
189
+ return this.handleFetch(req.entityId, req.identity);
190
190
  if (this.isPutRequest(req.methode, path))
191
- return this.handleReplace(req.entityId, entity, req.profileId);
191
+ return this.handleReplace(req.entityId, entity, req.identity);
192
192
  if (this.isPostRequest(req.methode, path))
193
- return this.handlePostCreate(entity, req.isAdmin, req.identity);
193
+ return this.handlePostCreate(entity, req.identity);
194
194
  if (this.isListRequest(req.methode, path))
195
195
  return this.handleList(req.methode, path, req.filter);
196
196
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"controller-api.js","sourceRoot":"","sources":["../../src/controller/controller-api.ts"],"names":[],"mappings":";;;AAAA,oCAiBkB;AAElB,4CAA2D;AAE3D,sDAAuD;AAGvD,MAAsB,aAAa;IACd,OAAO,CAAI;IACpB,MAAM,CAAe;I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;QACnD,IAAI,CAAC,MAAM;YAAE,OAAO;QAEpB,IAAI,CAAC;YACH,IAAA,0BAAkB,EAAC,MAAM,EAAE,WAAW,CAAC,CAAC;QAC1C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,eAAe,GAAG,IAAA,oBAAY,EAAC,KAAK,CAAC,CAAC;YAC5C,MAAM,IAAI,qBAAS,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,YAAY,EAAE,EAAE,eAAe,CAAC,CAAC;QAC3E,CAAC;IACH,CAAC;CACF;AAhUD,sCAgUC","sourcesContent":["import {\n Access,\n APIResponse,\n BaseEntity,\n createApiResponse,\n EndpointPolicy,\n Filter,\n findMatchedPolicy,\n formatErrors,\n HttpMethod,\n HttpRequest,\n List,\n parseHttpRequest,\n removeFields,\n RequestType,\n ResponseFields,\n validateWithSchema,\n} from \"../index\";\nimport { APIGatewayProxyEvent } from \"aws-lambda\";\nimport { errorHandlerHttp, ErrorHttp } from \"../exception\";\nimport { CognitoUser, EntityConfig } from \"@chinggis/types\";\nimport { trimSpecialChar } from \"../utils/string.util\";\nimport { CrudService } from \"../service\";\n\nexport abstract class ControllerApi<R extends BaseEntity, T extends CrudService<R>> {\n protected readonly service: T;\n protected config: EntityConfig;\n protected adminGroupNames: string[];\n\n protected constructor(baseService: T, config: EntityConfig) {\n this.service = baseService;\n\n if (!config) return;\n\n this.config = config;\n\n if (config.ADMIN_GROUP_NAME) {\n this.adminGroupNames = config.ADMIN_GROUP_NAME;\n }\n\n this.service.setConfig(config);\n }\n\n async resolveCrudRequest(event: APIGatewayProxyEvent): Promise<APIResponse> {\n try {\n let req = parseHttpRequest(event, this.adminGroupNames);\n\n const policy: EndpointPolicy | undefined = findMatchedPolicy(\n req.methode,\n event?.requestContext?.resourcePath,\n this.config.ENDPOINT_POLICY,\n );\n\n this.checkPermission(policy?.access, req.requestType);\n this.validateRequest(policy?.validator, req.body);\n\n log.debug(\"groups: \" + JSON.stringify(req.groups, null, 2));\n log.debug(`claims:${JSON.stringify(req.identity, null, 2)}`);\n log.debug(\n `groups:${req.groups}, isAdmin:${req.isAdmin}, userId:${req.userId}, profileId:${req.profileId}, username:${req.username}, requestType:${req.requestType}`,\n );\n\n // if (req.isAdmin) {\n // delete req.filter[\"profileId\"];\n // delete req.filter[\"ownerParentId\"];\n // }\n\n req = await this.processCrudRequestPre(req);\n\n let response: any = await this.handleCrudByMethod(req);\n\n if (response) response = await this.processCrudRequestPost(req, response);\n else response = await this.processCrudRequest(req); // Custom Endpoints\n\n if (!policy?.response) {\n return createApiResponse(200, response);\n }\n\n const filteredResponse = this.filterResponse(response, policy.response);\n\n return createApiResponse(200, filteredResponse);\n } catch (err) {\n const error = errorHandlerHttp(err);\n log.error(error);\n error.content.message = \"[CORE] \" + error.content.message;\n return createApiResponse(error.statusCode, error.content);\n }\n }\n\n setConfig(config: EntityConfig): void {\n this.config = config;\n }\n\n async processCrudRequestPre(req: HttpRequest): Promise<HttpRequest> {\n return req;\n }\n\n async processCrudRequestPost(request: HttpRequest, response: R | List<R>): Promise<R | List<R>> {\n return response;\n }\n\n protected async handleList(methode: HttpMethod, path: string, filter: Filter): Promise<any> {\n if (methode === \"GET\" && trimSpecialChar(path) === trimSpecialChar(this.config.BASE_PATH)) {\n return await this.service.find(filter || {});\n }\n\n if (methode === \"GET\" && trimSpecialChar(path) === trimSpecialChar(this.config.BASE_PATH) + \"/search\") {\n return await this.service.search(filter || {});\n }\n\n if (methode === \"GET\" && trimSpecialChar(path) === trimSpecialChar(this.config.BASE_PATH) + \"/scan\") {\n return await this.service.scan(filter || {});\n }\n }\n\n protected async handleUpdate(entityId: string, requestBody: any, profileId?: string): Promise<R> {\n if (!entityId)\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot PATCH resource without id field\");\n\n const entity = this.parseEntity(requestBody);\n\n if (Object.keys(entity).length === 0) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] No fields to update\");\n }\n\n const fieldName = this.config.DYNAMO_DB?.MAP?.partitionKey ?? \"id\";\n\n // id change is forbidden\n if (entity[fieldName]) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot modify the id field\");\n }\n\n entity[fieldName] = entityId;\n return this.service.update(entity as R, profileId);\n }\n\n protected async handleDelete(entityId: string, profileId?: string): Promise<boolean> {\n if (!entityId)\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot delete resource without id field\");\n\n return this.service.remove(entityId, profileId);\n }\n\n protected async handleFetch(entityId: string, profileId?: string): Promise<R> {\n if (!entityId)\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot fetch resource without id field\");\n\n const result = await this.service.findById(entityId, profileId);\n\n if (result) return result;\n\n throw new ErrorHttp({ code: 404, error: \"NotFound\" }, `[CORE] Resource with ID ${entityId} not found`);\n }\n\n protected async handleReplace(entityId: string, entity: any, profileId?: string) {\n if (!entityId)\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot PUT resource without id field\");\n\n if (!Object.keys(entity).length) {\n throw new ErrorHttp({ code: 400, error: \"Bad Request\" }, \"[CORE] No entity provided for PUT update\");\n }\n\n if (!entityId) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot PUT resource without id field\");\n }\n\n entity.id = entityId;\n\n return this.service.update(entity, profileId);\n }\n\n protected async handlePostCreate(entity: R, isAdmin: boolean, cognitoUser: CognitoUser) {\n if (!entity || Object.keys(entity).length === 0) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] No entity payload provided\");\n }\n\n if (!entity.ownerId) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] No ownerId provided\");\n }\n\n // Initialize IDs\n const { ownerId, ownerParentId: inputParentId } = entity;\n let profileId = ownerId;\n let parentId: string;\n\n // Determine parentId and profileId\n if (isAdmin && inputParentId) {\n parentId = inputParentId;\n } else if (cognitoUser.isParent) {\n console.log(\"is parent becomming true\");\n\n parentId = cognitoUser.profile;\n } else {\n console.log(\"is parent not becomming true\");\n console.log(\"the value of isParent: \", cognitoUser.isParent, typeof cognitoUser.isParent);\n\n parentId = cognitoUser.parentId;\n profileId = cognitoUser.profile;\n }\n\n // Remove fields that shouldn't be saved directly\n delete entity.ownerParentId;\n delete entity.ownerId;\n\n // Save entity\n return this.service.save(entity, profileId, parentId);\n }\n\n protected abstract processCrudRequest(event: HttpRequest): Promise<any>;\n\n protected isListRequest(methode: HttpMethod, path: string): boolean {\n const basePath = trimSpecialChar(this.config.BASE_PATH);\n\n const allowedPaths = [basePath, `${basePath}/search`, `${basePath}/scan`];\n\n const isMethodGet = methode === \"GET\";\n const isAllowedPath = allowedPaths.includes(trimSpecialChar(path));\n\n return isMethodGet && isAllowedPath;\n }\n\n protected isUpdateRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}/{id}`;\n const isMethodPatch = methode === \"PATCH\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodPatch && isExpectedPath;\n }\n\n protected isDeleteRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}/{id}`;\n const isMethodDelete = methode === \"DELETE\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodDelete && isExpectedPath;\n }\n\n protected isFetchRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}/{id}`;\n const isMethodGet = methode === \"GET\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodGet && isExpectedPath;\n }\n\n protected isPostRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}`;\n const isMethodGet = methode === \"POST\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodGet && isExpectedPath;\n }\n\n protected isPutRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}/{id}`;\n const isMethodGet = methode === \"PUT\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodGet && isExpectedPath;\n }\n\n private async handleCrudByMethod(req: HttpRequest): Promise<any> {\n const path = req.event?.requestContext?.resourcePath;\n\n const entity = this.parseEntity(req.body);\n\n if (this.isUpdateRequest(req.methode, path)) return this.handleUpdate(req.entityId, entity, req.profileId);\n if (this.isDeleteRequest(req.methode, path)) return this.handleDelete(req.entityId, req.profileId);\n if (this.isFetchRequest(req.methode, path)) return this.handleFetch(req.entityId, req.profileId);\n if (this.isPutRequest(req.methode, path)) return this.handleReplace(req.entityId, entity, req.profileId);\n if (this.isPostRequest(req.methode, path)) return this.handlePostCreate(entity, req.isAdmin, req.identity);\n if (this.isListRequest(req.methode, path)) return this.handleList(req.methode, path, req.filter);\n\n return null;\n }\n\n private filterResponse(response: any, responsePolicy: ResponseFields): any {\n if (Array.isArray(response)) {\n return removeFields(response, responsePolicy.include, responsePolicy.exclude);\n }\n\n if (response?.items && Array.isArray(response.items)) {\n response.items = removeFields(response.items, responsePolicy.include, responsePolicy.exclude);\n return response;\n }\n\n return removeFields([response], responsePolicy.include, responsePolicy.exclude)[0];\n }\n\n /** Map RequestType to Access for permission checking */\n private getUserAccessLevel(requestType: RequestType): Access {\n switch (requestType) {\n case RequestType.ADMIN:\n return Access.ADMIN;\n case RequestType.USER:\n return Access.USER;\n case RequestType.GUEST:\n return Access.PUBLIC;\n case RequestType.SYSTEM:\n return Access.SYSTEM;\n default:\n return Access.PUBLIC;\n }\n }\n\n /** Check if the user has permission for the current operation */\n private checkPermission(allowedAccess: Access[], requestType: RequestType) {\n const currentAccessLevel = this.getUserAccessLevel(requestType);\n\n // This means USER can access OWNER-level permissions, but the service will verify actual ownership\n const hasPermission =\n allowedAccess.includes(currentAccessLevel) ||\n (requestType === RequestType.USER && allowedAccess.includes(Access.OWNER));\n\n if (hasPermission) return;\n\n throw new ErrorHttp(\n { code: 403, error: \"PermissionDenied\" },\n `Access denied. Required: ${allowedAccess.join(\", \")}, Current: ${currentAccessLevel}`,\n );\n }\n\n private setUserFilter(request: any, isAdmin: boolean, profileId: string) {\n if (isAdmin && !profileId) return;\n const ownerIdFieldName = this.config.OWNER_ID_FIELD_NAME || \"ownerId\";\n request.filterAndSort[ownerIdFieldName] = profileId;\n return request.filterAndSort;\n }\n\n private parseEntity(requestBody: any): R {\n if (!requestBody) return {} as R;\n return typeof requestBody === \"string\" ? JSON.parse(requestBody) : requestBody;\n }\n\n private validateRequest(schema: any, requestBody: any) {\n if (!schema) return;\n\n try {\n validateWithSchema(schema, requestBody);\n } catch (error) {\n const formattedErrors = formatErrors(error);\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, formattedErrors);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"controller-api.js","sourceRoot":"","sources":["../../src/controller/controller-api.ts"],"names":[],"mappings":";;;AAAA,oCAiBkB;AAElB,4CAA2D;AAE3D,sDAAuD;AAGvD,MAAsB,aAAa;IACd,OAAO,CAAI;IACpB,MAAM,CAAe;IACrB,eAAe,CAAW;IAEpC,YAAsB,WAAc,EAAE,MAAoB;QACxD,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC;QAE3B,IAAI,CAAC,MAAM;YAAE,OAAO;QAEpB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAErB,IAAI,MAAM,CAAC,gBAAgB,EAAE,CAAC;YAC5B,IAAI,CAAC,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAAC;QACjD,CAAC;QAED,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,KAA2B;QAClD,IAAI,CAAC;YACH,IAAI,GAAG,GAAG,IAAA,wBAAgB,EAAC,KAAK,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;YAExD,MAA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formatErrors,\n HttpMethod,\n HttpRequest,\n List,\n parseHttpRequest,\n removeFields,\n RequestType,\n ResponseFields,\n validateWithSchema,\n} from \"../index\";\nimport { APIGatewayProxyEvent } from \"aws-lambda\";\nimport { errorHandlerHttp, ErrorHttp } from \"../exception\";\nimport { CognitoUser, EntityConfig } from \"@chinggis/types\";\nimport { trimSpecialChar } from \"../utils/string.util\";\nimport { CrudService } from \"../service\";\n\nexport abstract class ControllerApi<R extends BaseEntity, T extends CrudService<R>> {\n protected readonly service: T;\n protected config: EntityConfig;\n protected adminGroupNames: string[];\n\n protected constructor(baseService: T, config: EntityConfig) {\n this.service = baseService;\n\n if (!config) return;\n\n this.config = config;\n\n if (config.ADMIN_GROUP_NAME) {\n this.adminGroupNames = config.ADMIN_GROUP_NAME;\n }\n\n this.service.setConfig(config);\n }\n\n async resolveCrudRequest(event: APIGatewayProxyEvent): Promise<APIResponse> {\n try {\n let req = parseHttpRequest(event, this.adminGroupNames);\n\n const policy: EndpointPolicy | undefined = findMatchedPolicy(\n req.methode,\n event?.requestContext?.resourcePath,\n this.config.ENDPOINT_POLICY,\n );\n\n this.checkPermission(policy?.access, req.requestType);\n this.validateRequest(policy?.validator, req.body);\n\n log.debug(\"groups: \" + JSON.stringify(req.identity.groups, null, 2));\n log.debug(`claims:${JSON.stringify(req.identity, null, 2)}`);\n log.debug(\n `groups:${req.identity.groups}, isAdmin:${req.identity.isAdmin}, userId:${req.identity.sub}, profileId:${req.identity.profile}, username:${req.identity.username}, requestType:${req.requestType}`,\n );\n\n // if (req.isAdmin) {\n // delete req.filter[\"profileId\"];\n // delete req.filter[\"ownerParentId\"];\n // }\n\n req = await this.processCrudRequestPre(req);\n\n let response: any = await this.handleCrudByMethod(req);\n\n if (response) response = await this.processCrudRequestPost(req, response);\n else response = await this.processCrudRequest(req); // Custom Endpoints\n\n if (!policy?.response) {\n return createApiResponse(200, response);\n }\n\n const filteredResponse = this.filterResponse(response, policy.response);\n\n return createApiResponse(200, filteredResponse);\n } catch (err) {\n const error = errorHandlerHttp(err);\n log.error(error);\n error.content.message = \"[CORE] \" + error.content.message;\n return createApiResponse(error.statusCode, error.content);\n }\n }\n\n setConfig(config: EntityConfig): void {\n this.config = config;\n }\n\n async processCrudRequestPre(req: HttpRequest): Promise<HttpRequest> {\n return req;\n }\n\n async processCrudRequestPost(request: HttpRequest, response: R | List<R>): Promise<R | List<R>> {\n return response;\n }\n\n protected async handleList(methode: HttpMethod, path: string, filter: Filter): Promise<any> {\n if (methode === \"GET\" && trimSpecialChar(path) === trimSpecialChar(this.config.BASE_PATH)) {\n return await this.service.find(filter || {});\n }\n\n if (methode === \"GET\" && trimSpecialChar(path) === trimSpecialChar(this.config.BASE_PATH) + \"/search\") {\n return await this.service.search(filter || {});\n }\n\n if (methode === \"GET\" && trimSpecialChar(path) === trimSpecialChar(this.config.BASE_PATH) + \"/scan\") {\n return await this.service.scan(filter || {});\n }\n }\n\n protected async handleUpdate(entityId: string, requestBody: any, requestedUser?: CognitoUser): Promise<R> {\n if (!entityId)\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot PATCH resource without id field\");\n\n const entity = this.parseEntity(requestBody);\n\n if (Object.keys(entity).length === 0) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] No fields to update\");\n }\n\n const fieldName = this.config.DYNAMO_DB?.MAP?.partitionKey ?? \"id\";\n\n // id change is forbidden\n if (entity[fieldName]) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot modify the id field\");\n }\n\n entity[fieldName] = entityId;\n return this.service.update(entity as R, requestedUser);\n }\n\n protected async handleDelete(entityId: string, requestedUser?: CognitoUser): Promise<boolean> {\n if (!entityId)\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot delete resource without id field\");\n\n return this.service.remove(entityId, requestedUser);\n }\n\n protected async handleFetch(entityId: string, requestedUser?: CognitoUser): Promise<R> {\n if (!entityId)\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot fetch resource without id field\");\n\n const result = await this.service.findById(entityId, requestedUser);\n\n if (result) return result;\n\n throw new ErrorHttp({ code: 404, error: \"NotFound\" }, `[CORE] Resource with ID ${entityId} not found`);\n }\n\n protected async handleReplace(entityId: string, entity: any, requestedUser?: CognitoUser) {\n if (!entityId)\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot PUT resource without id field\");\n\n if (!Object.keys(entity).length) {\n throw new ErrorHttp({ code: 400, error: \"Bad Request\" }, \"[CORE] No entity provided for PUT update\");\n }\n\n if (!entityId) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] Cannot PUT resource without id field\");\n }\n\n entity.id = entityId;\n\n return this.service.update(entity, requestedUser);\n }\n\n protected async handlePostCreate(entity: R, cognitoUser: CognitoUser) {\n if (!entity || Object.keys(entity).length === 0) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] No entity payload provided\");\n }\n\n if (!entity.ownerId) {\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, \"[CORE] No ownerId provided\");\n }\n\n // Initialize IDs\n const { ownerId, ownerParentId: inputParentId } = entity;\n let profileId = ownerId;\n let parentId: string;\n\n // Determine parentId and profileId\n if (cognitoUser.isAdmin && inputParentId) {\n parentId = inputParentId;\n } else if (cognitoUser.isParent) {\n console.log(\"is parent becomming true\");\n\n parentId = cognitoUser.profile;\n } else {\n console.log(\"is parent not becomming true\");\n console.log(\"the value of isParent: \", cognitoUser.isParent, typeof cognitoUser.isParent);\n\n parentId = cognitoUser.parentId;\n profileId = cognitoUser.profile;\n }\n\n // Remove fields that shouldn't be saved directly\n delete entity.ownerParentId;\n delete entity.ownerId;\n\n // Save entity\n return this.service.save(entity, profileId, parentId);\n }\n\n protected abstract processCrudRequest(event: HttpRequest): Promise<any>;\n\n protected isListRequest(methode: HttpMethod, path: string): boolean {\n const basePath = trimSpecialChar(this.config.BASE_PATH);\n\n const allowedPaths = [basePath, `${basePath}/search`, `${basePath}/scan`];\n\n const isMethodGet = methode === \"GET\";\n const isAllowedPath = allowedPaths.includes(trimSpecialChar(path));\n\n return isMethodGet && isAllowedPath;\n }\n\n protected isUpdateRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}/{id}`;\n const isMethodPatch = methode === \"PATCH\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodPatch && isExpectedPath;\n }\n\n protected isDeleteRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}/{id}`;\n const isMethodDelete = methode === \"DELETE\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodDelete && isExpectedPath;\n }\n\n protected isFetchRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}/{id}`;\n const isMethodGet = methode === \"GET\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodGet && isExpectedPath;\n }\n\n protected isPostRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}`;\n const isMethodGet = methode === \"POST\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodGet && isExpectedPath;\n }\n\n protected isPutRequest(methode: HttpMethod, path: string): boolean {\n const expectedPath = `${trimSpecialChar(this.config.BASE_PATH)}/{id}`;\n const isMethodGet = methode === \"PUT\";\n const isExpectedPath = trimSpecialChar(path) === expectedPath;\n\n return isMethodGet && isExpectedPath;\n }\n\n private async handleCrudByMethod(req: HttpRequest): Promise<any> {\n const path = req.event?.requestContext?.resourcePath;\n\n const entity = this.parseEntity(req.body);\n\n if (this.isUpdateRequest(req.methode, path)) return this.handleUpdate(req.entityId, entity, req.identity);\n if (this.isDeleteRequest(req.methode, path)) return this.handleDelete(req.entityId, req.identity);\n if (this.isFetchRequest(req.methode, path)) return this.handleFetch(req.entityId, req.identity);\n if (this.isPutRequest(req.methode, path)) return this.handleReplace(req.entityId, entity, req.identity);\n if (this.isPostRequest(req.methode, path)) return this.handlePostCreate(entity, req.identity);\n if (this.isListRequest(req.methode, path)) return this.handleList(req.methode, path, req.filter);\n\n return null;\n }\n\n private filterResponse(response: any, responsePolicy: ResponseFields): any {\n if (Array.isArray(response)) {\n return removeFields(response, responsePolicy.include, responsePolicy.exclude);\n }\n\n if (response?.items && Array.isArray(response.items)) {\n response.items = removeFields(response.items, responsePolicy.include, responsePolicy.exclude);\n return response;\n }\n\n return removeFields([response], responsePolicy.include, responsePolicy.exclude)[0];\n }\n\n /** Map RequestType to Access for permission checking */\n private getUserAccessLevel(requestType: RequestType): Access {\n switch (requestType) {\n case RequestType.ADMIN:\n return Access.ADMIN;\n case RequestType.USER:\n return Access.USER;\n case RequestType.GUEST:\n return Access.PUBLIC;\n case RequestType.SYSTEM:\n return Access.SYSTEM;\n default:\n return Access.PUBLIC;\n }\n }\n\n /** Check if the user has permission for the current operation */\n private checkPermission(allowedAccess: Access[], requestType: RequestType) {\n const currentAccessLevel = this.getUserAccessLevel(requestType);\n\n // This means USER can access OWNER-level permissions, but the service will verify actual ownership\n const hasPermission =\n allowedAccess.includes(currentAccessLevel) ||\n (requestType === RequestType.USER && allowedAccess.includes(Access.OWNER));\n\n if (hasPermission) return;\n\n throw new ErrorHttp(\n { code: 403, error: \"PermissionDenied\" },\n `Access denied. Required: ${allowedAccess.join(\", \")}, Current: ${currentAccessLevel}`,\n );\n }\n\n private setUserFilter(request: any, isAdmin: boolean, profileId: string) {\n if (isAdmin && !profileId) return;\n const ownerIdFieldName = this.config.OWNER_ID_FIELD_NAME || \"ownerId\";\n request.filterAndSort[ownerIdFieldName] = profileId;\n return request.filterAndSort;\n }\n\n private parseEntity(requestBody: any): R {\n if (!requestBody) return {} as R;\n return typeof requestBody === \"string\" ? JSON.parse(requestBody) : requestBody;\n }\n\n private validateRequest(schema: any, requestBody: any) {\n if (!schema) return;\n\n try {\n validateWithSchema(schema, requestBody);\n } catch (error) {\n const formattedErrors = formatErrors(error);\n throw new ErrorHttp({ code: 400, error: \"BadRequest\" }, formattedErrors);\n }\n }\n}\n"]}
@@ -9,7 +9,18 @@ export interface BaseEntity {
9
9
  ownerId?: string;
10
10
  ownerParentId?: string;
11
11
  permission?: Map<string, Permission[]>;
12
- history?: any[];
12
+ history?: ChangeHistory[];
13
+ }
14
+ export interface ChangedField {
15
+ fieldName: string;
16
+ oldValue: string;
17
+ newValue: string;
18
+ }
19
+ export interface ChangeHistory {
20
+ action: string;
21
+ user: string;
22
+ date: string;
23
+ changes?: ChangedField[];
13
24
  }
14
25
  export interface Permission {
15
26
  role: RequestType;
@@ -1 +1 @@
1
- {"version":3,"file":"base.model.js","sourceRoot":"","sources":["../../src/model/base.model.ts"],"names":[],"mappings":"","sourcesContent":["import { RequestType } from \"./validation.model\";\nimport { Action } from \"./http.model\";\n\nexport interface BaseEntity {\n id?: string;\n createdAt?: string;\n updatedAt?: string;\n createdBy?: string | any;\n updatedBy?: string | any;\n ownerId?: string;\n ownerParentId?: string;\n permission?: Map<string, Permission[]>;\n history?: any[];\n}\n\nexport interface Permission {\n role: RequestType;\n actions: Action[];\n}\n\nexport interface Attachment {\n thumbnail: string;\n original: string;\n}\n\nexport interface List<T> {\n items: Array<T>;\n lastKey?: string;\n}\n"]}
1
+ {"version":3,"file":"base.model.js","sourceRoot":"","sources":["../../src/model/base.model.ts"],"names":[],"mappings":"","sourcesContent":["import { RequestType } from \"./validation.model\";\nimport { Action } from \"./http.model\";\n\nexport interface BaseEntity {\n id?: string;\n createdAt?: string;\n updatedAt?: string;\n createdBy?: string | any;\n updatedBy?: string | any;\n ownerId?: string;\n ownerParentId?: string;\n permission?: Map<string, Permission[]>;\n history?: ChangeHistory[];\n}\n\nexport interface ChangedField {\n fieldName: string;\n oldValue: string;\n newValue: string;\n}\n\nexport interface ChangeHistory {\n action: string;\n user: string;\n date: string;\n changes?: ChangedField[];\n}\n\nexport interface Permission {\n role: RequestType;\n actions: Action[];\n}\n\nexport interface Attachment {\n thumbnail: string;\n original: string;\n}\n\nexport interface List<T> {\n items: Array<T>;\n lastKey?: string;\n}\n"]}
@@ -27,8 +27,10 @@ export interface CognitoUser {
27
27
  identityId?: string;
28
28
  token_use?: TokenUse;
29
29
  profile?: string;
30
+ groups?: string[];
30
31
  parentId?: string;
31
32
  isParent?: number;
33
+ isAdmin?: boolean;
32
34
  email?: string;
33
35
  phone_number?: string;
34
36
  phone_number_verified?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"cognito-user.model.js","sourceRoot":"","sources":["../../src/model/cognito-user.model.ts"],"names":[],"mappings":";AAAA,wBAAwB;;;AAExB,iBAAiB;AACjB,IAAY,QAIX;AAJD,WAAY,QAAQ;IAClB,qBAAS,CAAA;IACT,6BAAiB,CAAA;IACjB,mDAAuC,CAAA;AACzC,CAAC,EAJW,QAAQ,wBAAR,QAAQ,QAInB;AAED,yCAAyC;AACzC,IAAY,iBAQX;AARD,WAAY,iBAAiB;IAC3B,gDAA2B,CAAA;IAC3B,4CAAuB,CAAA;IACvB,0CAAqB,CAAA;IACrB,gDAA2B,CAAA;IAC3B,wCAAmB,CAAA;IACnB,sDAAiC,CAAA;IACjC,oEAA+C,CAAA;AACjD,CAAC,EARW,iBAAiB,iCAAjB,iBAAiB,QAQ5B","sourcesContent":["// cognito-user.model.ts\n\n/** Token type */\nexport enum TokenUse {\n ID = \"id\",\n ACCESS = \"access\",\n PRE_AUTHORIZATION = \"pre-authorization\",\n}\n\n/** User status from Cognito Admin API */\nexport enum CognitoUserStatus {\n UNCONFIRMED = \"UNCONFIRMED\",\n CONFIRMED = \"CONFIRMED\",\n ARCHIVED = \"ARCHIVED\",\n COMPROMISED = \"COMPROMISED\",\n UNKNOWN = \"UNKNOWN\",\n RESET_REQUIRED = \"RESET_REQUIRED\",\n FORCE_CHANGE_PASSWORD = \"FORCE_CHANGE_PASSWORD\",\n}\n\n/** Full Cognito user type (JWT + Admin API) */\nexport interface CognitoUser {\n // JWT / token fields\n username?: string;\n sub?: string;\n iss?: string; // issuer\n name?: string;\n client_id?: string;\n aud?: string;\n exp?: string;\n Authorization?: string; // id token\n identityId?: string;\n token_use?: TokenUse;\n profile?: string;\n parentId?: string;\n isParent?: number;\n\n // Cognito Admin fields\n email?: string;\n phone_number?: string; // <- just declare the type, no assignment here\n phone_number_verified?: boolean;\n givenName?: string;\n middleName?: string;\n familyName?: string;\n gender?: string;\n nickname?: string;\n address?: string;\n birthdate?: string;\n picture?: string;\n preferred_username?: string;\n website?: string;\n zoneinfo?: string;\n enabled?: boolean;\n userStatus?: CognitoUserStatus;\n\n // Additional attributes\n attributes?: Record<string, string>;\n createdAt?: string;\n updatedAt?: string;\n}\n"]}
1
+ {"version":3,"file":"cognito-user.model.js","sourceRoot":"","sources":["../../src/model/cognito-user.model.ts"],"names":[],"mappings":";AAAA,wBAAwB;;;AAExB,iBAAiB;AACjB,IAAY,QAIX;AAJD,WAAY,QAAQ;IAClB,qBAAS,CAAA;IACT,6BAAiB,CAAA;IACjB,mDAAuC,CAAA;AACzC,CAAC,EAJW,QAAQ,wBAAR,QAAQ,QAInB;AAED,yCAAyC;AACzC,IAAY,iBAQX;AARD,WAAY,iBAAiB;IAC3B,gDAA2B,CAAA;IAC3B,4CAAuB,CAAA;IACvB,0CAAqB,CAAA;IACrB,gDAA2B,CAAA;IAC3B,wCAAmB,CAAA;IACnB,sDAAiC,CAAA;IACjC,oEAA+C,CAAA;AACjD,CAAC,EARW,iBAAiB,iCAAjB,iBAAiB,QAQ5B","sourcesContent":["// cognito-user.model.ts\n\n/** Token type */\nexport enum TokenUse {\n ID = \"id\",\n ACCESS = \"access\",\n PRE_AUTHORIZATION = \"pre-authorization\",\n}\n\n/** User status from Cognito Admin API */\nexport enum CognitoUserStatus {\n UNCONFIRMED = \"UNCONFIRMED\",\n CONFIRMED = \"CONFIRMED\",\n ARCHIVED = \"ARCHIVED\",\n COMPROMISED = \"COMPROMISED\",\n UNKNOWN = \"UNKNOWN\",\n RESET_REQUIRED = \"RESET_REQUIRED\",\n FORCE_CHANGE_PASSWORD = \"FORCE_CHANGE_PASSWORD\",\n}\n\n/** Full Cognito user type (JWT + Admin API) */\nexport interface CognitoUser {\n // JWT / token fields\n username?: string;\n sub?: string;\n iss?: string; // issuer\n name?: string;\n client_id?: string;\n aud?: string;\n exp?: string;\n Authorization?: string; // id token\n identityId?: string;\n token_use?: TokenUse;\n profile?: string;\n groups?: string[];\n parentId?: string;\n isParent?: number;\n isAdmin?: boolean;\n\n // Cognito Admin fields\n email?: string;\n phone_number?: string; // <- just declare the type, no assignment here\n phone_number_verified?: boolean;\n givenName?: string;\n middleName?: string;\n familyName?: string;\n gender?: string;\n nickname?: string;\n address?: string;\n birthdate?: string;\n picture?: string;\n preferred_username?: string;\n website?: string;\n zoneinfo?: string;\n enabled?: boolean;\n userStatus?: CognitoUserStatus;\n\n // Additional attributes\n attributes?: Record<string, string>;\n createdAt?: string;\n updatedAt?: string;\n}\n"]}
@@ -15,10 +15,10 @@ export declare abstract class CrudServiceImpl<T extends BaseEntity, D extends Ba
15
15
  searchFieldNotExist(fieldName: string, from: number, size: number): Promise<Partial<T>[]>;
16
16
  save(entity: Partial<T>, ownerId: string, parentId?: string, createdByUser?: string | CognitoUser): Promise<T>;
17
17
  saveAll(entities: Partial<T>[], ownerId: string, parentId?: string, createdByUser?: string | CognitoUser, isTransactional?: boolean): Promise<Partial<T>[]>;
18
- update(entity: T, requestUser?: string | CognitoUser): Promise<T>;
19
- updateAll(entities: Partial<T>[], fields: string[], requestUserId?: string, isTransactional?: boolean): Promise<boolean>;
20
- remove(entityId: string, ownerId?: string): Promise<boolean>;
21
- removeAll(entityIds: string[], ownerId?: string): Promise<boolean>;
18
+ update(entity: T, requestUser?: CognitoUser): Promise<T>;
19
+ updateAll(entities: Partial<T>[], fields: string[], requestUser?: CognitoUser, isTransactional?: boolean): Promise<boolean>;
20
+ remove(entityId: string, requestUser: CognitoUser): Promise<boolean>;
21
+ removeAll(entityIds: string[], requestUser: CognitoUser): Promise<boolean>;
22
22
  changeOwner(entityId: string, ownerId: string): Promise<T>;
23
23
  setTable(tableName: string, dynamoIndexMap: DynamoIndexMap): boolean;
24
24
  setOpensearch(indexName: string, opensearchEndpoint: string): boolean;
@@ -31,8 +31,8 @@ export declare abstract class CrudServiceImpl<T extends BaseEntity, D extends Ba
31
31
  findByField(fieldName: string, fieldValue: any): Promise<List<T>>;
32
32
  findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T>;
33
33
  find(filter: Filter): Promise<List<Partial<T>>>;
34
- findById(entityId: string, profileId?: string): Promise<T>;
35
- findByIds(entityIds: string[], profileId?: string): Promise<T[]>;
34
+ findById(entityId: string, requestUser?: CognitoUser): Promise<T>;
35
+ findByIds(entityIds: string[], requestUser: CognitoUser): Promise<T[]>;
36
36
  scan(filter: Filter): Promise<List<Partial<T>>>;
37
37
  throwErrorHttp(error: {
38
38
  message: string;
@@ -57,4 +57,5 @@ export declare abstract class CrudServiceImpl<T extends BaseEntity, D extends Ba
57
57
  private handleCreate;
58
58
  private handleUpdate;
59
59
  private addHistory;
60
+ private setIndexField;
60
61
  }
@@ -1,4 +1,4 @@
1
- import { BaseEntity, DynamoIndexMap, Filter, List } from "../index";
1
+ import { BaseEntity, CognitoUser, DynamoIndexMap, Filter, List } from "../index";
2
2
  import { EntityConfig } from "../model/index.js";
3
3
  /**
4
4
  * Defines a generic base service interface for working with entities in both
@@ -29,49 +29,49 @@ export interface CrudService<T extends BaseEntity> {
29
29
  /**
30
30
  * Applies partial updates to an entity for the given user.
31
31
  * Only the specified fields will be updated.
32
- * @param requestUserId - The ID of the user who owns the entity. If not exist means admin
32
+ * @param requestUser - Cognito user, system if not exist
33
33
  * @param entity - The entity with updated fields.
34
34
  * @returns The updated entity.
35
35
  */
36
- update(entity: T, requestUserId?: string): Promise<T>;
36
+ update(entity: T, requestUser?: CognitoUser): Promise<T>;
37
37
  /**
38
38
  * Applies partial updates to multiple entities for the given user.
39
39
  * Only the specified fields will be updated for each entity.
40
- * @param requestUserId - The ID of the user who owns the entities. If not exist means admin
40
+ * @param requestUser - Cognito user, system if not exist
41
41
  * @param entity - An array of entities with updated fields.
42
42
  * @param fields - The list of field names to update in each entity.
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
- updateAll(entity: T[], fields: string[], requestUserId?: string, isTransactional?: boolean): Promise<boolean>;
46
+ updateAll(entity: T[], fields: string[], requestUser?: CognitoUser, isTransactional?: boolean): Promise<boolean>;
47
47
  /**
48
48
  * Deletes an entity by ID for the given user.
49
- * @param ownerId - The ID of the user who owns the entity.
49
+ * @param requestUser - Cognito user, system if not exist
50
50
  * @param entityId - The ID of the entity to delete.
51
51
  * @returns True if the entity was successfully deleted.
52
52
  */
53
- remove(entityId: string, ownerId?: string): Promise<boolean>;
53
+ remove(entityId: string, requestUser?: CognitoUser): Promise<boolean>;
54
54
  /**
55
55
  * Deletes multiple entities by their IDs for the given user.
56
- * @param ownerId - The ID of the user who owns the entities.
56
+ * @param requestUser - Cognito user, system if not exist
57
57
  * @param entityIds - An array of entity IDs to delete.
58
58
  * @returns True if all entities were successfully deleted.
59
59
  */
60
- removeAll(entityIds: string[], ownerId?: string): Promise<boolean>;
60
+ removeAll(entityIds: string[], requestUser?: CognitoUser): Promise<boolean>;
61
61
  /**
62
62
  * Retrieves an entity by its ID for the given user.
63
- * @param ownerId - The ID of the user who owns the entity.
63
+ * @param requestUser - Cognito user, system if not exist
64
64
  * @param entityId - The ID of the entity to retrieve.
65
65
  * @returns The requested entity.
66
66
  */
67
- findById(entityId: string, ownerId?: string): Promise<T>;
67
+ findById(entityId: string, requestUser?: CognitoUser): Promise<T>;
68
68
  /**
69
69
  * Retrieves multiple entities by their IDs for the given user.
70
- * @param ownerId - The ID of the user who owns the entities.
70
+ * @param requestUser - Cognito user, system if not exist
71
71
  * @param entityIds - An array of entity IDs to retrieve.
72
72
  * @returns An array of found entities.
73
73
  */
74
- findByIds(entityIds: string[], ownerId?: string): Promise<T[]>;
74
+ findByIds(entityIds: string[], requestUser?: CognitoUser): Promise<T[]>;
75
75
  /**
76
76
  * Retrieves a paginated and filtered list of entities from DynamoDB.
77
77
  *
@@ -1 +1 @@
1
- {"version":3,"file":"crud.service.interface.js","sourceRoot":"","sources":["../../src/service/crud.service.interface.ts"],"names":[],"mappings":"","sourcesContent":["import { BaseEntity, 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 createdByUserId - The created userId.\n * @returns The created entity.\n */\n save(entity: Partial<T>, ownerId: string, parentId?: string, createdByUserId?: string): Promise<T>;\n\n /**\n * Creates multiple new entities for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entity - An array of entities to be created.\n * @param parentId\n * @param createdByUserId - The created userId.\n * @param isTransactional - Whether to perform the operation in a transaction.\n * @returns An array of created entities.\n */\n saveAll(\n entity: Partial<T>[],\n ownerId: string,\n parentId?: string,\n createdByUserId?: string,\n isTransactional?: boolean,\n ): Promise<Partial<T>[]>;\n\n /**\n * Applies partial updates to an entity for the given user.\n * Only the specified fields will be updated.\n * @param requestUserId - The ID of the user who owns the entity. If not exist means admin\n * @param entity - The entity with updated fields.\n * @returns The updated entity.\n */\n update(entity: T, requestUserId?: string): Promise<T>;\n\n /**\n * Applies partial updates to multiple entities for the given user.\n * Only the specified fields will be updated for each entity.\n * @param requestUserId - The ID of the user who owns the entities. If not exist means admin\n * @param entity - An array of entities with updated fields.\n * @param fields - The list of field names to update in each entity.\n * @param isTransactional - Whether to perform the operation in a transaction.\n * @returns True if all entities were successfully updated.\n */\n updateAll(entity: T[], fields: string[], requestUserId?: string, isTransactional?: boolean): Promise<boolean>;\n\n /**\n * Deletes an entity by ID for the given user.\n * @param ownerId - The ID of the user who owns the entity.\n * @param entityId - The ID of the entity to delete.\n * @returns True if the entity was successfully deleted.\n */\n remove(entityId: string, ownerId?: string): Promise<boolean>;\n\n /**\n * Deletes multiple entities by their IDs for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entityIds - An array of entity IDs to delete.\n * @returns True if all entities were successfully deleted.\n */\n removeAll(entityIds: string[], ownerId?: string): Promise<boolean>;\n\n /**\n * Retrieves an entity by its ID for the given user.\n * @param ownerId - The ID of the user who owns the entity.\n * @param entityId - The ID of the entity to retrieve.\n * @returns The requested entity.\n */\n findById(entityId: string, ownerId?: string): Promise<T>;\n\n /**\n * Retrieves multiple entities by their IDs for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entityIds - An array of entity IDs to retrieve.\n * @returns An array of found entities.\n */\n findByIds(entityIds: string[], ownerId?: string): Promise<T[]>;\n\n /**\n * Retrieves a paginated and filtered list of entities from DynamoDB.\n *\n * @param filter - Filtering and sorting options.\n * @returns A promise resolving to a paginated list of entities.\n */\n find(filter: Filter): Promise<List<Partial<T>>>;\n\n /**\n * Scans the table with non-index filters. Expensive; avoid it for hot paths.\n */\n scan(filter: Filter): Promise<List<Partial<T>>>;\n\n findQuery(queryParams: string): Promise<List<Partial<T>>>;\n\n searchQuery(queryParams: string): Promise<Partial<T>[]>;\n\n findAll(): Promise<T[]>;\n\n findAllMatch(filter: Filter): Promise<T[]>;\n\n findAllByIndex(indexName: string, indexValue: any): Promise<T[]>;\n\n findByField(fieldName: string, fieldValue: any): Promise<List<T>>;\n\n findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T>;\n\n throwError(code: number, message: string, errorContent?: any): void;\n\n throwErrorHttp(error: { message: string; code: number }, message: string, errorContent?: any): void;\n\n throwErrorDatabase(tableName: string, command: any, errorContent?: any): void;\n\n throwErrorValidation(entityName: string, validation: Map<string, any>, errorContent?: any): void;\n\n // throwError(httpStatus: number, message: string): void;\n /**\n * Retrieves a filtered and sorted list of entities from OpenSearch.\n *\n * @param filter - Filtering and sorting options.\n * @returns A promise resolving to the list of matching entities.\n */\n search(filter: Filter): Promise<T[]>;\n\n searchFieldNotExist(fieldName: string, from: number, size: number): Promise<Partial<T>[]>;\n\n /**\n * Changes the owner of an entity.\n * @param ownerId - The new owner's ID.\n * @param entityId - The ID of the entity to transfer.\n * @returns The updated entity with the new owner.\n */\n changeOwner(entityId: string, ownerId: string): Promise<T>;\n\n setTable(tableName: string, dynamoIndexMap: DynamoIndexMap): boolean;\n\n setOpensearch(indexName: string, opensearchEndpoint: string): boolean;\n\n getIndexES(): string;\n\n getIndexMapDB(): DynamoIndexMap;\n\n 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 createdByUserId - The created userId.\n * @returns The created entity.\n */\n save(entity: Partial<T>, ownerId: string, parentId?: string, createdByUserId?: string): Promise<T>;\n\n /**\n * Creates multiple new entities for the given user.\n * @param ownerId - The ID of the user who owns the entities.\n * @param entity - An array of entities to be created.\n * @param parentId\n * @param createdByUserId - The created userId.\n * @param isTransactional - Whether to perform the operation in a transaction.\n * @returns An array of created entities.\n */\n saveAll(\n entity: Partial<T>[],\n ownerId: string,\n parentId?: string,\n createdByUserId?: string,\n isTransactional?: boolean,\n ): Promise<Partial<T>[]>;\n\n /**\n * Applies partial updates to an entity for the given user.\n * Only the specified fields will be updated.\n * @param requestUser - Cognito user, system if not exist\n * @param entity - The entity with updated fields.\n * @returns The updated entity.\n */\n update(entity: T, requestUser?: CognitoUser): 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 /**\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 /**\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): Promise<List<Partial<T>>>;\n\n /**\n * Scans the table with non-index filters. Expensive; avoid it for hot paths.\n */\n scan(filter: Filter): Promise<List<Partial<T>>>;\n\n findQuery(queryParams: string): Promise<List<Partial<T>>>;\n\n searchQuery(queryParams: string): Promise<Partial<T>[]>;\n\n findAll(): Promise<T[]>;\n\n findAllMatch(filter: Filter): Promise<T[]>;\n\n findAllByIndex(indexName: string, indexValue: any): Promise<T[]>;\n\n findByField(fieldName: string, fieldValue: any): Promise<List<T>>;\n\n findFirst(fieldName: string, fieldValue: string | boolean | number | Date): Promise<T>;\n\n throwError(code: number, message: string, errorContent?: any): void;\n\n throwErrorHttp(error: { message: string; code: number }, message: string, errorContent?: any): void;\n\n throwErrorDatabase(tableName: string, command: any, errorContent?: any): void;\n\n throwErrorValidation(entityName: string, validation: Map<string, any>, errorContent?: any): void;\n\n // throwError(httpStatus: number, message: string): void;\n /**\n * Retrieves a filtered and sorted list of entities from OpenSearch.\n *\n * @param filter - Filtering and sorting options.\n * @returns A promise resolving to the list of matching entities.\n */\n search(filter: Filter): Promise<T[]>;\n\n searchFieldNotExist(fieldName: string, from: number, size: number): Promise<Partial<T>[]>;\n\n /**\n * Changes the owner of an entity.\n * @param ownerId - The new owner's ID.\n * @param entityId - The ID of the entity to transfer.\n * @returns The updated entity with the new owner.\n */\n changeOwner(entityId: string, ownerId: string): Promise<T>;\n\n setTable(tableName: string, dynamoIndexMap: DynamoIndexMap): boolean;\n\n setOpensearch(indexName: string, opensearchEndpoint: string): boolean;\n\n getIndexES(): string;\n\n getIndexMapDB(): DynamoIndexMap;\n\n 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"]}