storemw-core-api 1.0.21 → 1.0.22
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/controllers/injection_field/injectionFieldController.js +48 -27
- package/dist/controllers/injection_field/injectionFieldController.js.map +1 -1
- package/dist/models/ModelFactory.d.ts +2 -1
- package/dist/models/ModelFactory.js +12 -6
- package/dist/models/ModelFactory.js.map +1 -1
- package/dist/models/account/AccountModel.d.ts +2 -1
- package/dist/models/branch/BranchModel.d.ts +2 -1
- package/dist/models/branch_user/BranchUserModel.d.ts +2 -1
- package/dist/models/business/BusinessModel.d.ts +2 -1
- package/dist/models/group/GroupModel.d.ts +2 -1
- package/dist/models/group/GroupOwnerModel.d.ts +2 -1
- package/dist/models/injection_field/DocumentInjectionFieldModel.d.ts +2 -1
- package/dist/models/injection_field/InjectionFieldModel.d.ts +2 -1
- package/dist/models/injection_field/ItemInjectionFieldModel.d.ts +2 -1
- package/dist/models/injection_field/LogisticInjectionFieldModel.d.ts +2 -1
- package/dist/models/injection_field/RepositoryInjectionFieldModel.d.ts +2 -1
- package/dist/models/injection_field/UserInjectionFieldModel.d.ts +2 -1
- package/dist/models/item/BrandModel.d.ts +2 -1
- package/dist/models/item/CategoryModel.d.ts +2 -1
- package/dist/models/item/ItemModel.d.ts +2 -1
- package/dist/models/item/ProductModel.d.ts +2 -1
- package/dist/models/item/UomModel.d.ts +2 -1
- package/dist/models/location/LocationModel.d.ts +2 -1
- package/dist/models/location/LocationRackModel.d.ts +2 -1
- package/dist/models/location/LocationSlotModel.d.ts +2 -1
- package/dist/models/region/AreaModel.d.ts +2 -1
- package/dist/models/region/CountryModel.d.ts +2 -1
- package/dist/models/region/StateModel.d.ts +2 -1
- package/dist/models/user/AdministratorModel.d.ts +2 -1
- package/dist/models/user/CustomerModel.d.ts +2 -1
- package/dist/models/user/RetailerModel.d.ts +2 -1
- package/dist/models/user/UserModel.d.ts +2 -1
- package/dist/models/user/UserPropModel.d.ts +2 -1
- package/dist/models/user/UserStatusModel.d.ts +2 -1
- package/dist/models/user/WorkerModel.d.ts +2 -1
- package/dist/schema/payload/injection_field/schemaInjectionField.d.ts +509 -33
- package/dist/schema/payload/injection_field/schemaInjectionField.js +53 -23
- package/dist/schema/payload/injection_field/schemaInjectionField.js.map +1 -1
- package/dist/services/injection_field/DocumentInjectionFieldService.d.ts +1 -53
- package/dist/services/injection_field/DocumentInjectionFieldService.js +21 -4
- package/dist/services/injection_field/DocumentInjectionFieldService.js.map +1 -1
- package/dist/services/injection_field/ItemInjectionFieldService.d.ts +5 -54
- package/dist/services/injection_field/ItemInjectionFieldService.js +54 -12
- package/dist/services/injection_field/ItemInjectionFieldService.js.map +1 -1
- package/dist/services/injection_field/LogisticInjectionFieldService.d.ts +1 -14
- package/dist/services/injection_field/LogisticInjectionFieldService.js +21 -4
- package/dist/services/injection_field/LogisticInjectionFieldService.js.map +1 -1
- package/dist/services/injection_field/RepositoryInjectionFieldService.d.ts +1 -19
- package/dist/services/injection_field/RepositoryInjectionFieldService.js +21 -4
- package/dist/services/injection_field/RepositoryInjectionFieldService.js.map +1 -1
- package/dist/services/injection_field/UserInjectionFieldService.d.ts +1 -29
- package/dist/services/injection_field/UserInjectionFieldService.js +21 -4
- package/dist/services/injection_field/UserInjectionFieldService.js.map +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +2 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/schemaUtils.d.ts +1 -0
- package/dist/utils/schemaUtils.js +14 -1
- package/dist/utils/schemaUtils.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LogisticInjectionFieldService.js","sourceRoot":"","sources":["../../../src/services/injection_field/LogisticInjectionFieldService.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"LogisticInjectionFieldService.js","sourceRoot":"","sources":["../../../src/services/injection_field/LogisticInjectionFieldService.ts"],"names":[],"mappings":";;;AAAA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WAAW,EAAE,SAAS,CAAC,CAAA;QAE/E,IAAI,mBAAmB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACjC,MAAM,KAAK,CAAC,6BAA6B,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QAC9H,CAAC;QAED,0BAA0B;QAC1B,IAAI,MAAM,GAAG,MAAM,2BAA2B,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,CAAA;QAE7D,IAAI,QAAQ,GAAQ,EAAE,CAAA;QAEtB,IAAI,MAAM,EAAE,CAAC,CAAC,kBAAkB;YAE5B,8BAA8B;YAC9B,OAAO,SAAS,CAAC,YAAY,CAAC;YAC9B,OAAO,SAAS,CAAC,SAAS,CAAC;YAC3B,OAAO,SAAS,CAAC,OAAO,CAAC;YACzB,OAAO,SAAS,CAAC,SAAS,CAAC;YAC3B,QAAQ,GAAG,MAAM,2BAA2B,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,CAAA;QAE1G,CAAC;aAAM,CAAC,CAAC,aAAa;YAClB,QAAQ,GAAG,MAAM,2BAA2B,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;QAC5E,CAAC;QAED,OAAO,QAAQ,CAAA;IACnB,CAAC,CAAA;IAED,OAAO;QACH,6BAA6B;KAChC,CAAA;AAEL,CAAC,CAAA;AArEY,QAAA,6BAA6B,iCAqEzC","sourcesContent":["import {\n LogisticInjectionFieldModel,\n ModelLogisticInjectionFieldFields,\n} from \"@/models\";\n\nimport { DefaultServiceProps } from \"@/utils\";\n\nimport { convertPayloadByTableSchema, validateModelFieldsWithData } from \"@/utils\";\n\ntype LogisticInjectionFieldMap = {\n transporter: {\n logistic: { logisticId: any };\n };\n};\n\ntype LogisticInjectionFieldModule = keyof LogisticInjectionFieldMap;\n// type LogisticInjectionFieldRef<M extends LogisticInjectionFieldModule> = keyof LogisticInjectionFieldMap[M];\n\nexport const logisticModulePrefixMap: Record<LogisticInjectionFieldModule, string> = {\n transporter: \"tpt\"\n};\n\nexport const logisticRefPrefixMap: Record<\"logistic\", string> = {\n logistic: \"lgt\"\n};\n\nexport type LogisticInjectionFieldModuleRef = {\n [M in LogisticInjectionFieldModule]: {\n [R in keyof LogisticInjectionFieldMap[M]]: {\n module: M;\n ref: R;\n } & LogisticInjectionFieldMap[M][R];\n }[keyof LogisticInjectionFieldMap[M]];\n}[LogisticInjectionFieldModule];\n\nexport type LogisticInjectionFieldServiceProps = DefaultServiceProps & {};\n\nexport type LogisticInjectionFieldRemoveProps = {\n ids: number[]\n};\n\nexport type LogisticInjectionFieldReplaceProps = {\n data: LogisticInjectionFieldModuleRef & {\n fields: any\n }\n}\n\nconst getReplacePayload = (data: LogisticInjectionFieldReplaceProps[\"data\"]) => {\n\n let { module, ref, logisticId } = data\n\n let payload: Record<string, any> = {};\n\n payload = {\n ...payload,\n ...{\n [`${ModelLogisticInjectionFieldFields.field_module}`]: module,\n [`${ModelLogisticInjectionFieldFields.field_ref}`]: ref,\n }\n }\n\n if (\"logisticId\" in data) {\n payload = { ...payload, ...(data?.logisticId ? { [`${ModelLogisticInjectionFieldFields.logistic_id}`]: logisticId } : {}) }\n }\n\n // if (\"branchId\" in data) {\n // const branchId = data.branchId\n // payload = { ...payload, ...(data?.branchId ? { [`${ModelLogisticInjectionFieldFields.branch_id}`]: branchId } : {}) }\n // }\n\n // if (\"memberId\" in data) {\n // const memberId = data.memberId\n // payload = { ...payload, ...(data?.memberId ? { [`${ModelLogisticInjectionFieldFields.member_id}`]: memberId } : {}) }\n // }\n\n const rest = data.fields\n\n // apply dynamic prefix: refPrefix_modulePrefix_fieldKey\n const refPrefix = logisticRefPrefixMap[ref as keyof typeof logisticRefPrefixMap] ?? ref;\n const modulePrefix = logisticModulePrefixMap[module as LogisticInjectionFieldModule] ?? module;\n\n for (const [key, value] of Object.entries(rest)) {\n payload[`${refPrefix}_${modulePrefix}_${key}`] = value;\n }\n\n return payload\n\n}\n\nexport const LogisticInjectionFieldService = (props: LogisticInjectionFieldServiceProps) => {\n\n const {\n prisma,\n accountId = 0,\n actionUserId = 0\n } = props\n\n const logisticInjectionFieldModel = LogisticInjectionFieldModel({ prisma, accountId, actionUserId })\n\n const replaceLogisticInjectionField = async ({ data }: LogisticInjectionFieldReplaceProps) => {\n\n const _data = getReplacePayload(data)\n\n if (!_data) {\n throw new Error(`Invalid create payload: ${JSON.stringify(_data)}`);\n }\n\n const where: Record<string, any> = {\n [ModelLogisticInjectionFieldFields.field_module]: data.module,\n [ModelLogisticInjectionFieldFields.field_ref]: data.ref,\n ...(data?.logisticId ? { [ModelLogisticInjectionFieldFields.logistic_id]: data.logisticId } : {}),\n };\n\n // Narrow: only include branchId if data.ref === \"branch\"\n // if (data.ref === \"branch\") {\n // where[ModelLogisticInjectionFieldFields.branch_id] = (data as Extract<LogisticInjectionFieldModuleRef, { ref: \"branch\" }>).branchId;\n // }\n\n let modelFields = await logisticInjectionFieldModel.getFields()\n\n let finalData = convertPayloadByTableSchema(_data, modelFields)\n\n // console.log('modelFields', modelFields)\n // console.log('finalData', finalData)\n\n\n // check the request fields are in the exactly schema\n const resultInvalidFields = validateModelFieldsWithData(modelFields, finalData)\n\n if (resultInvalidFields.length > 0) {\n throw Error(`Invalid injection fields: ${resultInvalidFields.join(\", \")} (Request: ${Object.keys(finalData).join(\", \")})`)\n }\n\n // check the record exists\n let exists = await logisticInjectionFieldModel.get({ where })\n\n let response: any = {}\n\n if (exists) { // update existing\n\n // remove unwanted to override\n delete finalData.field_module;\n delete finalData.field_ref;\n delete finalData.user_id;\n delete finalData.branch_id;\n response = await logisticInjectionFieldModel.update({ data: finalData, where, disableRollback: true })\n\n } else { // create new\n response = await logisticInjectionFieldModel.create({ data: finalData })\n }\n\n return response\n }\n\n return {\n replaceLogisticInjectionField\n }\n\n}\n\n\n"]}
|
|
@@ -38,24 +38,6 @@ export type RepositoryInjectionFieldReplaceProps = {
|
|
|
38
38
|
};
|
|
39
39
|
};
|
|
40
40
|
export declare const RepositoryInjectionFieldService: (props: RepositoryInjectionFieldServiceProps) => {
|
|
41
|
-
replaceRepositoryInjectionField: ({ data }: RepositoryInjectionFieldReplaceProps) => Promise<
|
|
42
|
-
createdatetime: Date | null;
|
|
43
|
-
createuserid: bigint;
|
|
44
|
-
updatedatetime: Date | null;
|
|
45
|
-
updateuserid: bigint;
|
|
46
|
-
isdelete: boolean | null;
|
|
47
|
-
istrash: boolean | null;
|
|
48
|
-
accountid: bigint;
|
|
49
|
-
field_module: string | null;
|
|
50
|
-
field_ref: string | null;
|
|
51
|
-
repository_injection_field_id: bigint;
|
|
52
|
-
repository_id: bigint;
|
|
53
|
-
repository_item_id: bigint | null;
|
|
54
|
-
cont_repo_tes: import("@prisma/client/runtime/library").Decimal | null;
|
|
55
|
-
repo_cont_repo_t3es: import("@prisma/client/runtime/library").Decimal | null;
|
|
56
|
-
repo_pk_pk_cont: import("@prisma/client/runtime/library").Decimal | null;
|
|
57
|
-
repo_itme_pk_pk_cont_item: import("@prisma/client/runtime/library").Decimal | null;
|
|
58
|
-
repo_itme_cont_pk_cont_item: import("@prisma/client/runtime/library").Decimal | null;
|
|
59
|
-
}>;
|
|
41
|
+
replaceRepositoryInjectionField: ({ data }: RepositoryInjectionFieldReplaceProps) => Promise<any>;
|
|
60
42
|
};
|
|
61
43
|
export {};
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
// import { logError, throwError } from "../../utils";
|
|
3
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
3
|
exports.RepositoryInjectionFieldService = exports.repositoryRefPrefixMap = exports.repositoryModulePrefixMap = void 0;
|
|
5
4
|
const models_1 = require("../../models");
|
|
@@ -54,9 +53,27 @@ const RepositoryInjectionFieldService = (props) => {
|
|
|
54
53
|
// }
|
|
55
54
|
let modelFields = await repositoryInjectionFieldModel.getFields();
|
|
56
55
|
let finalData = (0, utils_1.convertPayloadByTableSchema)(_data, modelFields);
|
|
57
|
-
console.log('modelFields', modelFields)
|
|
58
|
-
console.log('finalData', finalData)
|
|
59
|
-
|
|
56
|
+
// console.log('modelFields', modelFields)
|
|
57
|
+
// console.log('finalData', finalData)
|
|
58
|
+
// check the request fields are in the exactly schema
|
|
59
|
+
const resultInvalidFields = (0, utils_1.validateModelFieldsWithData)(modelFields, finalData);
|
|
60
|
+
if (resultInvalidFields.length > 0) {
|
|
61
|
+
throw Error(`Invalid injection fields: ${resultInvalidFields.join(", ")} (Request: ${Object.keys(finalData).join(", ")})`);
|
|
62
|
+
}
|
|
63
|
+
// check the record exists
|
|
64
|
+
let exists = await repositoryInjectionFieldModel.get({ where });
|
|
65
|
+
let response = {};
|
|
66
|
+
if (exists) { // update existing
|
|
67
|
+
// remove unwanted to override
|
|
68
|
+
delete finalData.field_module;
|
|
69
|
+
delete finalData.field_ref;
|
|
70
|
+
delete finalData.repository_id;
|
|
71
|
+
delete finalData.repository_item_id;
|
|
72
|
+
response = await repositoryInjectionFieldModel.update({ data: finalData, where, disableRollback: true });
|
|
73
|
+
}
|
|
74
|
+
else { // create new
|
|
75
|
+
response = await repositoryInjectionFieldModel.create({ data: finalData });
|
|
76
|
+
}
|
|
60
77
|
return response;
|
|
61
78
|
};
|
|
62
79
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RepositoryInjectionFieldService.js","sourceRoot":"","sources":["../../../src/services/injection_field/RepositoryInjectionFieldService.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"RepositoryInjectionFieldService.js","sourceRoot":"","sources":["../../../src/services/injection_field/RepositoryInjectionFieldService.ts"],"names":[],"mappings":";;;AAAA,qCAGkB;AAIlB,mCAAmF;AAcnF,qHAAqH;AAExG,QAAA,yBAAyB,GAAmD;IACrF,OAAO,EAAE,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cAAc,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QAC9H,CAAC;QAED,0BAA0B;QAC1B,IAAI,MAAM,GAAG,MAAM,6BAA6B,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,CAAA;QAE/D,IAAI,QAAQ,GAAQ,EAAE,CAAA;QAEtB,IAAI,MAAM,EAAE,CAAC,CAAC,kBAAkB;YAE5B,8BAA8B;YAC9B,OAAO,SAAS,CAAC,YAAY,CAAC;YAC9B,OAAO,SAAS,CAAC,SAAS,CAAC;YAC3B,OAAO,SAAS,CAAC,aAAa,CAAC;YAC/B,OAAO,SAAS,CAAC,kBAAkB,CAAC;YAEpC,QAAQ,GAAG,MAAM,6BAA6B,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,CAAA;QAE5G,CAAC;aAAM,CAAC,CAAC,aAAa;YAClB,QAAQ,GAAG,MAAM,6BAA6B,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;QAC9E,CAAC;QAED,OAAO,QAAQ,CAAA;IACnB,CAAC,CAAA;IAED,OAAO;QACH,+BAA+B;KAClC,CAAA;AAEL,CAAC,CAAA;AAtEY,QAAA,+BAA+B,mCAsE3C","sourcesContent":["import {\n RepositoryInjectionFieldModel,\n ModelRepositoryInjectionFieldFields,\n} from \"@/models\";\n\nimport { DefaultServiceProps } from \"@/utils\";\n\nimport { convertPayloadByTableSchema, validateModelFieldsWithData } from \"@/utils\";\n\ntype RepositoryInjectionFieldMap = {\n package: {\n repository: { repositoryId: any };\n repository_item: { repositoryId: any; };\n };\n container: {\n repository: { repositoryId: any };\n repository_item: { repositoryId: any; };\n };\n};\n\ntype RepositoryInjectionFieldModule = keyof RepositoryInjectionFieldMap;\n// type RepositoryInjectionFieldRef<M extends RepositoryInjectionFieldModule> = keyof RepositoryInjectionFieldMap[M];\n\nexport const repositoryModulePrefixMap: Record<RepositoryInjectionFieldModule, string> = {\n package: \"pk\",\n container: \"cont\",\n};\n\nexport const repositoryRefPrefixMap: Record<\"repository\" | \"repository_item\", string> = {\n repository: \"repo\",\n repository_item: \"repo_item\",\n};\n\nexport type RepositoryInjectionFieldModuleRef = {\n [M in RepositoryInjectionFieldModule]: {\n [R in keyof RepositoryInjectionFieldMap[M]]: {\n module: M;\n ref: R;\n } & RepositoryInjectionFieldMap[M][R];\n }[keyof RepositoryInjectionFieldMap[M]];\n}[RepositoryInjectionFieldModule];\n\nexport type RepositoryInjectionFieldServiceProps = DefaultServiceProps & {};\n\nexport type RepositoryInjectionFieldRemoveProps = {\n ids: number[]\n};\n\nexport type RepositoryInjectionFieldReplaceProps = {\n data: RepositoryInjectionFieldModuleRef & {\n fields: any\n }\n}\n\nconst getReplacePayload = (data: RepositoryInjectionFieldReplaceProps[\"data\"]) => {\n\n let { module, ref, repositoryId } = data\n\n let payload: Record<string, any> = {};\n\n payload = {\n ...payload,\n ...{\n [`${ModelRepositoryInjectionFieldFields.field_module}`]: module,\n [`${ModelRepositoryInjectionFieldFields.field_ref}`]: ref,\n }\n }\n\n if (\"repositoryId\" in data) {\n payload = { ...payload, ...(data?.repositoryId ? { [`${ModelRepositoryInjectionFieldFields.repository_id}`]: repositoryId } : {}) }\n }\n\n const rest = data.fields\n\n // apply dynamic prefix: refPrefix_modulePrefix_fieldKey\n const refPrefix = repositoryRefPrefixMap[ref as keyof typeof repositoryRefPrefixMap] ?? ref;\n const modulePrefix = repositoryModulePrefixMap[module as RepositoryInjectionFieldModule] ?? module;\n\n for (const [key, value] of Object.entries(rest)) {\n payload[`${refPrefix}_${modulePrefix}_${key}`] = value;\n }\n\n return payload\n\n}\n\nexport const RepositoryInjectionFieldService = (props: RepositoryInjectionFieldServiceProps) => {\n\n const {\n prisma,\n accountId = 0,\n actionUserId = 0\n } = props\n\n const repositoryInjectionFieldModel = RepositoryInjectionFieldModel({ prisma, accountId, actionUserId })\n\n const replaceRepositoryInjectionField = async ({ data }: RepositoryInjectionFieldReplaceProps) => {\n\n const _data = getReplacePayload(data)\n\n if (!_data) {\n throw new Error(`Invalid create payload: ${JSON.stringify(_data)}`);\n }\n\n const where: Record<string, any> = {\n [ModelRepositoryInjectionFieldFields.field_module]: data.module,\n [ModelRepositoryInjectionFieldFields.field_ref]: data.ref,\n ...(data?.repositoryId ? { [ModelRepositoryInjectionFieldFields.repository_id]: data.repositoryId } : {}),\n };\n\n // Narrow: only include branchId if data.ref === \"branch\"\n // if (data.ref === \"branch\") {\n // where[ModelRepositoryInjectionFieldFields.branch_id] = (data as Extract<RepositoryInjectionFieldModuleRef, { ref: \"branch\" }>).branchId;\n // }\n\n let modelFields = await repositoryInjectionFieldModel.getFields()\n\n let finalData = convertPayloadByTableSchema(_data, modelFields)\n\n // console.log('modelFields', modelFields)\n // console.log('finalData', finalData)\n\n\n // check the request fields are in the exactly schema\n const resultInvalidFields = validateModelFieldsWithData(modelFields, finalData)\n\n if (resultInvalidFields.length > 0) {\n throw Error(`Invalid injection fields: ${resultInvalidFields.join(\", \")} (Request: ${Object.keys(finalData).join(\", \")})`)\n }\n\n // check the record exists\n let exists = await repositoryInjectionFieldModel.get({ where })\n\n let response: any = {}\n\n if (exists) { // update existing\n\n // remove unwanted to override\n delete finalData.field_module;\n delete finalData.field_ref;\n delete finalData.repository_id;\n delete finalData.repository_item_id;\n\n response = await repositoryInjectionFieldModel.update({ data: finalData, where, disableRollback: true })\n\n } else { // create new\n response = await repositoryInjectionFieldModel.create({ data: finalData })\n }\n\n return response\n }\n\n return {\n replaceRepositoryInjectionField\n }\n\n}\n\n\n"]}
|
|
@@ -65,34 +65,6 @@ export type UserInjectionFieldReplaceProps = {
|
|
|
65
65
|
};
|
|
66
66
|
};
|
|
67
67
|
export declare const UserInjectionFieldService: (props: UserInjectionFieldServiceProps) => {
|
|
68
|
-
replaceUserInjectionField: ({ data }: UserInjectionFieldReplaceProps) => Promise<
|
|
69
|
-
user_id: bigint;
|
|
70
|
-
createdatetime: Date | null;
|
|
71
|
-
createuserid: bigint;
|
|
72
|
-
updatedatetime: Date | null;
|
|
73
|
-
updateuserid: bigint;
|
|
74
|
-
isdelete: boolean | null;
|
|
75
|
-
istrash: boolean | null;
|
|
76
|
-
accountid: bigint;
|
|
77
|
-
branch_id: bigint | null;
|
|
78
|
-
member_id: bigint | null;
|
|
79
|
-
field_module: string | null;
|
|
80
|
-
field_ref: string | null;
|
|
81
|
-
user_injection_field_id: bigint;
|
|
82
|
-
usr_cust_cust_qty: bigint | null;
|
|
83
|
-
br_cust_branch_qty: bigint | null;
|
|
84
|
-
usr_cust_customer_branch_marking: string | null;
|
|
85
|
-
br_cust_customer_branch_marking: string | null;
|
|
86
|
-
usr_cust_customer_marking: string | null;
|
|
87
|
-
br_cust_postcode: string | null;
|
|
88
|
-
usr_cust_source_agent_remid: string | null;
|
|
89
|
-
usr_cust_source_client_remid: string | null;
|
|
90
|
-
br_cust_source_marking_remid: string | null;
|
|
91
|
-
usr_cust_source_profile_type: string | null;
|
|
92
|
-
br_cust_branch3_qty: import("@prisma/client/runtime/library").Decimal | null;
|
|
93
|
-
usr_mb_member_test: bigint | null;
|
|
94
|
-
removed_usr_cust_222333223: Date | null;
|
|
95
|
-
removed_br_ret_4sdfsdfd7s: string | null;
|
|
96
|
-
}>;
|
|
68
|
+
replaceUserInjectionField: ({ data }: UserInjectionFieldReplaceProps) => Promise<any>;
|
|
97
69
|
};
|
|
98
70
|
export {};
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
// import { logError, throwError } from "../../utils";
|
|
3
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
3
|
exports.UserInjectionFieldService = exports.userRefPrefixMap = exports.userModulePrefixMap = void 0;
|
|
5
4
|
const models_1 = require("../../models");
|
|
@@ -67,9 +66,27 @@ const UserInjectionFieldService = (props) => {
|
|
|
67
66
|
}
|
|
68
67
|
let modelFields = await userInjectionFieldModel.getFields();
|
|
69
68
|
let finalData = (0, utils_1.convertPayloadByTableSchema)(_data, modelFields);
|
|
70
|
-
console.log('modelFields', modelFields)
|
|
71
|
-
console.log('finalData', finalData)
|
|
72
|
-
|
|
69
|
+
// console.log('modelFields', modelFields)
|
|
70
|
+
// console.log('finalData', finalData)
|
|
71
|
+
// check the request fields are in the exactly schema
|
|
72
|
+
const resultInvalidFields = (0, utils_1.validateModelFieldsWithData)(modelFields, finalData);
|
|
73
|
+
if (resultInvalidFields.length > 0) {
|
|
74
|
+
throw Error(`Invalid injection fields: ${resultInvalidFields.join(", ")} (Request: ${Object.keys(finalData).join(", ")})`);
|
|
75
|
+
}
|
|
76
|
+
// check the record exists
|
|
77
|
+
let exists = await userInjectionFieldModel.get({ where });
|
|
78
|
+
let response = {};
|
|
79
|
+
if (exists) { // update existing
|
|
80
|
+
// remove unwanted to override
|
|
81
|
+
delete finalData.field_module;
|
|
82
|
+
delete finalData.field_ref;
|
|
83
|
+
delete finalData.user_id;
|
|
84
|
+
delete finalData.branch_id;
|
|
85
|
+
response = await userInjectionFieldModel.update({ data: finalData, where, disableRollback: true });
|
|
86
|
+
}
|
|
87
|
+
else { // create new
|
|
88
|
+
response = await userInjectionFieldModel.create({ data: finalData });
|
|
89
|
+
}
|
|
73
90
|
return response;
|
|
74
91
|
};
|
|
75
92
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserInjectionFieldService.js","sourceRoot":"","sources":["../../../src/services/injection_field/UserInjectionFieldService.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"UserInjectionFieldService.js","sourceRoot":"","sources":["../../../src/services/injection_field/UserInjectionFieldService.ts"],"names":[],"mappings":";;;AAAA,qCAGkB;AAIlB,mCAAmF;AA8BnF,mGAAmG;AAEtF,QAAA,mBAAmB,GAA6C;IACzE,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,KAAK;IACf,aAAa,EAAE,OA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AE3B,QAAQ,GAAG,MAAM,uBAAuB,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,CAAA;QAEtG,CAAC;aAAM,CAAC,CAAC,aAAa;YAClB,QAAQ,GAAG,MAAM,uBAAuB,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;QACxE,CAAC;QAED,OAAO,QAAQ,CAAA;IACnB,CAAC,CAAA;IAED,OAAO;QACH,yBAAyB;KAC5B,CAAA;AAEL,CAAC,CAAA;AArEY,QAAA,yBAAyB,6BAqErC","sourcesContent":["import {\n UserInjectionFieldModel,\n ModelUserInjectionFieldFields,\n} from \"@/models\";\n\nimport { DefaultServiceProps } from \"@/utils\";\n\nimport { convertPayloadByTableSchema, validateModelFieldsWithData } from \"@/utils\";\n\ntype UserInjectionFieldMap = {\n customer: {\n user: { userId: any };\n branch: { userId: any; branchId: any };\n };\n retailer: {\n user: { userId: any };\n branch: { userId: any; branchId: any };\n };\n administrator: {\n user: { userId: any };\n };\n supplier: {\n user: { userId: any };\n };\n driver: {\n user: { userId: any };\n };\n worker: {\n user: { userId: any };\n };\n member: {\n // user: { userId: any, memberId: any };\n user: { userId: any };\n };\n};\n\ntype UserInjectionFieldModule = keyof UserInjectionFieldMap;\n// type UserInjectionFieldRef<M extends UserInjectionFieldModule> = keyof UserInjectionFieldMap[M];\n\nexport const userModulePrefixMap: Record<UserInjectionFieldModule, string> = {\n customer: \"cust\",\n retailer: \"ret\",\n administrator: \"admin\",\n supplier: \"sup\",\n driver: \"drv\",\n worker: \"wrk\",\n member: \"mb\",\n};\n\nexport const userRefPrefixMap: Record<\"user\" | \"branch\", string> = {\n user: \"usr\",\n branch: \"br\",\n};\n\nexport type UserInjectionFieldModuleRef = {\n [M in UserInjectionFieldModule]: {\n [R in keyof UserInjectionFieldMap[M]]: {\n module: M;\n ref: R;\n } & UserInjectionFieldMap[M][R];\n }[keyof UserInjectionFieldMap[M]];\n}[UserInjectionFieldModule];\n\nexport type UserInjectionFieldServiceProps = DefaultServiceProps & {};\n\nexport type UserInjectionFieldRemoveProps = {\n ids: number[]\n};\n\nexport type UserInjectionFieldReplaceProps = {\n data: UserInjectionFieldModuleRef & {\n fields: any\n }\n}\n\nconst getReplacePayload = (data: UserInjectionFieldReplaceProps[\"data\"]) => {\n\n let { module, ref, userId } = data\n\n let payload: Record<string, any> = {};\n\n payload = {\n ...payload,\n ...{\n [`${ModelUserInjectionFieldFields.field_module}`]: module,\n [`${ModelUserInjectionFieldFields.field_ref}`]: ref,\n }\n }\n\n if (\"userId\" in data) {\n payload = { ...payload, ...(data?.userId ? { [`${ModelUserInjectionFieldFields.user_id}`]: userId } : {}) }\n }\n\n if (\"branchId\" in data) {\n const branchId = data.branchId\n payload = { ...payload, ...(data?.branchId ? { [`${ModelUserInjectionFieldFields.branch_id}`]: branchId } : {}) }\n }\n\n if (\"memberId\" in data) {\n const memberId = data.memberId\n payload = { ...payload, ...(data?.memberId ? { [`${ModelUserInjectionFieldFields.member_id}`]: memberId } : {}) }\n }\n\n const rest = data.fields\n\n // apply dynamic prefix: refPrefix_modulePrefix_fieldKey\n const refPrefix = userRefPrefixMap[ref as keyof typeof userRefPrefixMap] ?? ref;\n const modulePrefix = userModulePrefixMap[module as UserInjectionFieldModule] ?? module;\n\n for (const [key, value] of Object.entries(rest)) {\n payload[`${refPrefix}_${modulePrefix}_${key}`] = value;\n }\n\n return payload\n\n}\n\nexport const UserInjectionFieldService = (props: UserInjectionFieldServiceProps) => {\n\n const {\n prisma,\n accountId = 0,\n actionUserId = 0\n } = props\n\n const userInjectionFieldModel = UserInjectionFieldModel({ prisma, accountId, actionUserId })\n\n const replaceUserInjectionField = async ({ data }: UserInjectionFieldReplaceProps) => {\n\n const _data = getReplacePayload(data)\n\n if (!_data) {\n throw new Error(`Invalid create payload: ${JSON.stringify(_data)}`);\n }\n\n const where: Record<string, any> = {\n [ModelUserInjectionFieldFields.field_module]: data.module,\n [ModelUserInjectionFieldFields.field_ref]: data.ref,\n ...(data?.userId ? { [ModelUserInjectionFieldFields.user_id]: data.userId } : {}),\n };\n\n // Narrow: only include branchId if data.ref === \"branch\"\n if (data.ref === \"branch\") {\n where[ModelUserInjectionFieldFields.branch_id] = (data as Extract<UserInjectionFieldModuleRef, { ref: \"branch\" }>).branchId;\n }\n\n let modelFields = await userInjectionFieldModel.getFields()\n\n let finalData = convertPayloadByTableSchema(_data, modelFields)\n\n // console.log('modelFields', modelFields)\n // console.log('finalData', finalData)\n\n // check the request fields are in the exactly schema\n const resultInvalidFields = validateModelFieldsWithData(modelFields, finalData)\n\n if (resultInvalidFields.length > 0) {\n throw Error(`Invalid injection fields: ${resultInvalidFields.join(\", \")} (Request: ${Object.keys(finalData).join(\", \")})`)\n }\n\n // check the record exists\n let exists = await userInjectionFieldModel.get({ where })\n\n let response: any = {}\n\n if (exists) { // update existing\n\n // remove unwanted to override\n delete finalData.field_module;\n delete finalData.field_ref;\n delete finalData.user_id;\n delete finalData.branch_id;\n\n response = await userInjectionFieldModel.update({ data: finalData, where, disableRollback: true })\n\n } else { // create new\n response = await userInjectionFieldModel.create({ data: finalData })\n }\n\n return response\n }\n\n return {\n replaceUserInjectionField\n }\n\n}\n\n\n"]}
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export { default as _ } from "lodash";
|
|
|
2
2
|
export { HTTP_STATUS, sendError, sendSuccess } from "./responseUtils";
|
|
3
3
|
export { dayjs, getCurrentDateTime, getCurrentDateTimeISO } from "./dateUtils";
|
|
4
4
|
export { buildPrismaWhere } from "../helpers/prismaHelper";
|
|
5
|
-
export { validateWithSchema, validateMultipleSchemas, convertPayloadByTableSchema } from "./schemaUtils";
|
|
5
|
+
export { validateWithSchema, validateMultipleSchemas, convertPayloadByTableSchema, validateModelFieldsWithData } from "./schemaUtils";
|
|
6
6
|
export { default as logger } from "./logUtils";
|
|
7
7
|
export { throwError, logError } from "./exceptionUtils";
|
|
8
8
|
export { getSwmAuth } from "./smwUtils";
|
package/dist/utils/index.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.verifyPassword = exports.hashPassword = exports.generateAuthToken = exports.buildFullFieldName = exports.getDefaultServiceProps = exports.getFieldsByType = exports.buildSqlOrderBy = exports.buildSqlLimitOffset = exports.buildSqlWhere = exports.buildSqlSelect = exports.buildSqlRelation = exports.buildSqlRawSelect = exports.toFieldMap = exports.getFormattedZodErrorsIntoString = exports.getFormattedZodErrors = exports.checkRequestContentIsEmpty = exports.getRequestHeaderLocCode = exports.getSwmAuth = exports.logError = exports.throwError = exports.logger = exports.convertPayloadByTableSchema = exports.validateMultipleSchemas = exports.validateWithSchema = exports.buildPrismaWhere = exports.getCurrentDateTimeISO = exports.getCurrentDateTime = exports.dayjs = exports.sendSuccess = exports.sendError = exports.HTTP_STATUS = exports._ = void 0;
|
|
6
|
+
exports.verifyPassword = exports.hashPassword = exports.generateAuthToken = exports.buildFullFieldName = exports.getDefaultServiceProps = exports.getFieldsByType = exports.buildSqlOrderBy = exports.buildSqlLimitOffset = exports.buildSqlWhere = exports.buildSqlSelect = exports.buildSqlRelation = exports.buildSqlRawSelect = exports.toFieldMap = exports.getFormattedZodErrorsIntoString = exports.getFormattedZodErrors = exports.checkRequestContentIsEmpty = exports.getRequestHeaderLocCode = exports.getSwmAuth = exports.logError = exports.throwError = exports.logger = exports.validateModelFieldsWithData = exports.convertPayloadByTableSchema = exports.validateMultipleSchemas = exports.validateWithSchema = exports.buildPrismaWhere = exports.getCurrentDateTimeISO = exports.getCurrentDateTime = exports.dayjs = exports.sendSuccess = exports.sendError = exports.HTTP_STATUS = exports._ = void 0;
|
|
7
7
|
var lodash_1 = require("lodash");
|
|
8
8
|
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return __importDefault(lodash_1).default; } });
|
|
9
9
|
var responseUtils_1 = require("./responseUtils");
|
|
@@ -20,6 +20,7 @@ var schemaUtils_1 = require("./schemaUtils");
|
|
|
20
20
|
Object.defineProperty(exports, "validateWithSchema", { enumerable: true, get: function () { return schemaUtils_1.validateWithSchema; } });
|
|
21
21
|
Object.defineProperty(exports, "validateMultipleSchemas", { enumerable: true, get: function () { return schemaUtils_1.validateMultipleSchemas; } });
|
|
22
22
|
Object.defineProperty(exports, "convertPayloadByTableSchema", { enumerable: true, get: function () { return schemaUtils_1.convertPayloadByTableSchema; } });
|
|
23
|
+
Object.defineProperty(exports, "validateModelFieldsWithData", { enumerable: true, get: function () { return schemaUtils_1.validateModelFieldsWithData; } });
|
|
23
24
|
var logUtils_1 = require("./logUtils");
|
|
24
25
|
Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return __importDefault(logUtils_1).default; } });
|
|
25
26
|
var exceptionUtils_1 = require("./exceptionUtils");
|
package/dist/utils/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;;;;AAAA,iCAAsC;AAA7B,4GAAA,OAAO,OAAK;AACrB,iDAAsE;AAA7D,4GAAA,WAAW,OAAA;AAAE,0GAAA,SAAS,OAAA;AAAE,4GAAA,WAAW,OAAA;AAC5C,yCAA+E;AAAtE,kGAAA,KAAK,OAAA;AAAE,+GAAA,kBAAkB,OAAA;AAAE,kHAAA,qBAAqB,OAAA;AACzD,wDAA2D;AAAlD,gHAAA,gBAAgB,OAAA;AACzB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;;;;AAAA,iCAAsC;AAA7B,4GAAA,OAAO,OAAK;AACrB,iDAAsE;AAA7D,4GAAA,WAAW,OAAA;AAAE,0GAAA,SAAS,OAAA;AAAE,4GAAA,WAAW,OAAA;AAC5C,yCAA+E;AAAtE,kGAAA,KAAK,OAAA;AAAE,+GAAA,kBAAkB,OAAA;AAAE,kHAAA,qBAAqB,OAAA;AACzD,wDAA2D;AAAlD,gHAAA,gBAAgB,OAAA;AACzB,6CAAsI;AAA7H,iHAAA,kBAAkB,OAAA;AAAE,sHAAA,uBAAuB,OAAA;AAAE,0HAAA,2BAA2B,OAAA;AAAE,0HAAA,2BAA2B,OAAA;AAC9G,uCAA+C;AAAtC,mHAAA,OAAO,OAAU;AAC1B,mDAAwD;AAA/C,4GAAA,UAAU,OAAA;AAAE,0GAAA,QAAQ,OAAA;AAC7B,uCAAwC;AAA/B,sGAAA,UAAU,OAAA;AACnB,+CAAqF;AAA5E,uHAAA,uBAAuB,OAAA;AAAE,0HAAA,0BAA0B,OAAA;AAC5D,mEAAmE;AACnE,mDAAmD;AACnD,uCAAmF;AAA1E,iHAAA,qBAAqB,OAAA;AAAE,2HAAA,+BAA+B,OAAA;AAC/D,+CAAsK;AAA7J,0GAAA,UAAU,OAAA;AAAE,iHAAA,iBAAiB,OAAA;AAAE,gHAAA,gBAAgB,OAAA;AAAE,8GAAA,cAAc,OAAA;AAAE,6GAAA,aAAa,OAAA;AAAE,mHAAA,mBAAmB,OAAA;AAAE,+GAAA,eAAe,OAAA;AAAE,+GAAA,eAAe,OAAA;AAG9I,+CAAuD;AAA9C,sHAAA,sBAAsB,OAAA;AAC/B,6DAA0D;AAAjD,yHAAA,kBAAkB,OAAA;AAC3B,yCAA+C;AAAtC,8GAAA,iBAAiB,OAAA;AAC1B,iDAA8D;AAArD,6GAAA,YAAY,OAAA;AAAE,+GAAA,cAAc,OAAA","sourcesContent":["export { default as _ } from \"lodash\";\nexport { HTTP_STATUS, sendError, sendSuccess } from \"./responseUtils\";\nexport { dayjs, getCurrentDateTime, getCurrentDateTimeISO } from \"./dateUtils\";\nexport { buildPrismaWhere } from \"../helpers/prismaHelper\";\nexport { validateWithSchema, validateMultipleSchemas, convertPayloadByTableSchema, validateModelFieldsWithData } from \"./schemaUtils\";\nexport { default as logger } from \"./logUtils\";\nexport { throwError, logError } from \"./exceptionUtils\";\nexport { getSwmAuth } from \"./smwUtils\";\nexport { getRequestHeaderLocCode, checkRequestContentIsEmpty } from \"./requestUtils\";\n// export { storeJwtInMemory, getJwtFromMemory } from \"./jwtUtils\";\n// export { resizeImageBuffer } from \"./shapeUtils\"\nexport { getFormattedZodErrors, getFormattedZodErrorsIntoString } from \"./zodUtils\"\nexport { toFieldMap, buildSqlRawSelect, buildSqlRelation, buildSqlSelect, buildSqlWhere, buildSqlLimitOffset, buildSqlOrderBy, getFieldsByType } from \"./queryBuilder\"\n\nexport type { DefaultServiceProps } from \"./serviceUtils\"\nexport { getDefaultServiceProps } from \"./serviceUtils\"\nexport { buildFullFieldName } from \"./injectionFieldUtils\"\nexport { generateAuthToken } from \"./authUtils\"\nexport { hashPassword, verifyPassword } from \"./passwordUtils\""]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.convertPayloadByTableSchema = exports.validateMultipleSchemas = exports.validateWithSchema = void 0;
|
|
3
|
+
exports.validateModelFieldsWithData = exports.convertPayloadByTableSchema = exports.validateMultipleSchemas = exports.validateWithSchema = void 0;
|
|
4
4
|
const utils_1 = require("../utils");
|
|
5
5
|
const utils_2 = require("../utils");
|
|
6
6
|
/**
|
|
@@ -93,4 +93,17 @@ const convertPayloadByTableSchema = (payload, tableSchema) => {
|
|
|
93
93
|
return result;
|
|
94
94
|
};
|
|
95
95
|
exports.convertPayloadByTableSchema = convertPayloadByTableSchema;
|
|
96
|
+
// check the modelFields with data exists
|
|
97
|
+
const validateModelFieldsWithData = (modelFields, data) => {
|
|
98
|
+
let resultInvalidFields = [];
|
|
99
|
+
let modelFieldKeys = modelFields.map((i) => i.name);
|
|
100
|
+
Object.keys(data).forEach(i => {
|
|
101
|
+
let check = modelFieldKeys.includes(i);
|
|
102
|
+
if (check === false) {
|
|
103
|
+
resultInvalidFields.push(i);
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
return resultInvalidFields;
|
|
107
|
+
};
|
|
108
|
+
exports.validateModelFieldsWithData = validateModelFieldsWithData;
|
|
96
109
|
//# sourceMappingURL=schemaUtils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schemaUtils.js","sourceRoot":"","sources":["../../src/utils/schemaUtils.ts"],"names":[],"mappings":";;;AAEA,mCAAiD;AACjD,mCAAgD;AAEhD;;;;GAIG;AACI,MAAM,kBAAkB,GAAG,CAC9B,MAAiB,EACjB,SAAsC,QAAQ,EAChD,EAAE,CAAC,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAQ,EAAE;IAE3D,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IAE7C,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,eAAe,GAAG,IAAA,6BAAqB,EAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAE5D,IAAA,iBAAS,EACL,GAAG,EACH,aAAa,EACb,WAAW,MAAM,EAAE,EACnB,EAAE,EACF,GAAG,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,EAAE,EACpC,mBAAW,CAAC,WAAW,CAC1B,CAAC;QACF,OAAO;IACX,CAAC;IAED,kDAAkD;IACjD,GAAW,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC;IAEnC,4BAA4B;IAC5B,sCAAsC;IACtC,WAAW;IACX,uCAAuC;IACvC,IAAI;IAEJ,IAAI,EAAE,CAAC;AACX,CAAC,CAAC;AA/BW,QAAA,kBAAkB,sBA+B7B;AAEF;;;GAGG;AACI,MAAM,uBAAuB,GAAG,CACnC,OAAmD,EACrD,EAAE;IACA,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;QACv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,QAAQ,UAAU,EAAE,CAAC;YACjB,KAAK,QAAQ,CAAC;YACd,KAAK,SAAS,CAAC;YACf,KAAK,UAAU,CAAC;YAChB,KAAK,SAAS,CAAC;YACf,KAAK,SAAS;gBACV,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;gBAC5B,MAAM;YACV,KAAK,SAAS;gBACV,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,GAAG,CAAC;gBAChD,MAAM;YACV,KAAK,6BAA6B,CAAC;YACnC,KAAK,0BAA0B,CAAC;YAChC,KAAK,MAAM;gBACP,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;gBAC9B,MAAM;YACV,KAAK,MAAM,CAAC;YACZ,KAAK,OAAO;gBACR,IAAI,CAAC;oBACD,MAAM,CAAC,GAAG,CAAC,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;gBACxE,CAAC;gBAAC,MAAM,CAAC;oBACL,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;gBACxB,CAAC;gBACD,MAAM;YACV;gBACI,kBAAkB;gBAClB,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;gBACpB,MAAM;QACd,CAAC;IACL,CAAC;IAED,OAAO,MAAM,CAAC;AAClB,CAAC,CAAA;AAhDY,QAAA,2BAA2B,+BAgDvC","sourcesContent":["import { Request, Response, NextFunction } from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { sendError, HTTP_STATUS } from \"@/utils\";\nimport { getFormattedZodErrors } from \"@/utils\";\n\n/**\n * Creates a validation middleware from a given Zod schema.\n * @param schema Zod schema to validate against\n * @param source where to validate from (default: \"params\")\n */\nexport const validateWithSchema = (\n schema: ZodSchema,\n source: \"params\" | \"query\" | \"body\" = \"params\"\n) => (req: Request, res: Response, next: NextFunction): void => {\n\n const result = schema.safeParse(req[source]);\n\n if (!result.success) {\n const formattedErrors = getFormattedZodErrors(result.error);\n\n sendError(\n res,\n \"BAD_REQUEST\",\n `Invalid ${source}`,\n \"\",\n `${JSON.stringify(formattedErrors)}`,\n HTTP_STATUS.BAD_REQUEST\n );\n return;\n }\n\n // overwrite request object with parsed+typed data\n (req as any)[source] = result.data;\n\n // if (source === \"query\") {\n // req.query = result.data as any;\n // } else {\n // req.params = result.data as any;\n // }\n\n next();\n};\n\n/**\n * Middleware to validate multiple schemas in order.\n * @param schemas Array of tuples: [ZodSchema, source]\n */\nexport const validateMultipleSchemas = (\n schemas: [ZodSchema, \"params\" | \"query\" | \"body\"][]\n) => {\n return (req: Request, res: Response, next: NextFunction) => {\n let i = 0;\n\n const runNext = () => {\n if (i >= schemas.length) return next(); // all schemas validated\n\n const [schema, source] = schemas[i];\n i++;\n\n validateWithSchema(schema, source)(req, res, (err) => {\n if (err) return; // already handled by validateWithSchema\n runNext(); // validate next schema\n });\n };\n\n runNext();\n };\n};\n\n\n/**\n * Convert a payload object based on a table schema.\n * Automatically converts strings to number, boolean, Date, JSON if needed.\n */\nexport const convertPayloadByTableSchema = (\n payload: Record<string, any>,\n tableSchema: { name: string; type: string }[]\n): Record<string, any> => {\n const columnTypeMap = Object.fromEntries(\n tableSchema.map(c => [c.name, c.type])\n );\n\n const numericTypes = ['bigint', 'integer', 'smallint', 'numeric', 'decimal'];\n\n const result: Record<string, any> = { ...payload };\n\n for (const [key, value] of Object.entries(payload)) {\n const columnType = columnTypeMap[key];\n if (!columnType || value === null || value === undefined) continue;\n\n switch (columnType) {\n case 'bigint':\n case 'integer':\n case 'smallint':\n case 'numeric':\n case 'decimal':\n result[key] = Number(value);\n break;\n case 'boolean':\n result[key] = value === 'true' || value === '1';\n break;\n case 'timestamp without time zone':\n case 'timestamp with time zone':\n case 'date':\n result[key] = new Date(value);\n break;\n case 'json':\n case 'jsonb':\n try {\n result[key] = typeof value === 'string' ? JSON.parse(value) : value;\n } catch {\n result[key] = value;\n }\n break;\n default:\n // leave as string\n result[key] = value;\n break;\n }\n }\n\n return result;\n}"]}
|
|
1
|
+
{"version":3,"file":"schemaUtils.js","sourceRoot":"","sources":["../../src/utils/schemaUtils.ts"],"names":[],"mappings":";;;AAEA,mCAAiD;AACjD,mCAAgD;AAEhD;;;;GAIG;AACI,MAAM,kBAAkB,GAAG,CAC9B,MAAiB,EACjB,SAAsC,QAAQ,EAChD,EAAE,CAAC,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAQ,EAAE;IAE3D,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IAE7C,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,eAAe,GAAG,IAAA,6BAAqB,EAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAE5D,IAAA,iBAAS,EACL,GAAG,EACH,aAAa,EACb,WAAW,MAAM,EAAE,EACnB,EAAE,EACF,GAAG,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,EAAE,EACpC,mBAAW,CAAC,WAAW,CAC1B,CAAC;QACF,OAAO;IACX,CAAC;IAED,kDAAkD;IACjD,GAAW,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC;IAEnC,4BAA4B;IAC5B,sCAAsC;IACtC,WAAW;IACX,uCAAuC;IACvC,IAAI;IAEJ,IAAI,EAAE,CAAC;AACX,CAAC,CAAC;AA/BW,QAAA,kBAAkB,sBA+B7B;AAEF;;;GAGG;AACI,MAAM,uBAAuB,GAAG,CACnC,OAAmD,EACrD,EAAE;IACA,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;QACvD,IAAI,CAAC,GAAG,CAAC,CAAC;QAEV,MAAM,OAAO,GAAG,GAAG,EAAE;YACjB,IAAI,CAAC,IAAI,OAAO,CAAC,MA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C,CAAA;QACtC,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;YAClB,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QAC/B,CAAC;IACL,CAAC,CAAC,CAAA;IAEF,OAAO,mBAAmB,CAAA;AAC9B,CAAC,CAAA;AAbY,QAAA,2BAA2B,+BAavC","sourcesContent":["import { Request, Response, NextFunction } from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { sendError, HTTP_STATUS } from \"@/utils\";\nimport { getFormattedZodErrors } from \"@/utils\";\n\n/**\n * Creates a validation middleware from a given Zod schema.\n * @param schema Zod schema to validate against\n * @param source where to validate from (default: \"params\")\n */\nexport const validateWithSchema = (\n schema: ZodSchema,\n source: \"params\" | \"query\" | \"body\" = \"params\"\n) => (req: Request, res: Response, next: NextFunction): void => {\n\n const result = schema.safeParse(req[source]);\n\n if (!result.success) {\n const formattedErrors = getFormattedZodErrors(result.error);\n\n sendError(\n res,\n \"BAD_REQUEST\",\n `Invalid ${source}`,\n \"\",\n `${JSON.stringify(formattedErrors)}`,\n HTTP_STATUS.BAD_REQUEST\n );\n return;\n }\n\n // overwrite request object with parsed+typed data\n (req as any)[source] = result.data;\n\n // if (source === \"query\") {\n // req.query = result.data as any;\n // } else {\n // req.params = result.data as any;\n // }\n\n next();\n};\n\n/**\n * Middleware to validate multiple schemas in order.\n * @param schemas Array of tuples: [ZodSchema, source]\n */\nexport const validateMultipleSchemas = (\n schemas: [ZodSchema, \"params\" | \"query\" | \"body\"][]\n) => {\n return (req: Request, res: Response, next: NextFunction) => {\n let i = 0;\n\n const runNext = () => {\n if (i >= schemas.length) return next(); // all schemas validated\n\n const [schema, source] = schemas[i];\n i++;\n\n validateWithSchema(schema, source)(req, res, (err) => {\n if (err) return; // already handled by validateWithSchema\n runNext(); // validate next schema\n });\n };\n\n runNext();\n };\n};\n\n\n/**\n * Convert a payload object based on a table schema.\n * Automatically converts strings to number, boolean, Date, JSON if needed.\n */\nexport const convertPayloadByTableSchema = (\n payload: Record<string, any>,\n tableSchema: { name: string; type: string }[]\n): Record<string, any> => {\n const columnTypeMap = Object.fromEntries(\n tableSchema.map(c => [c.name, c.type])\n );\n\n const numericTypes = ['bigint', 'integer', 'smallint', 'numeric', 'decimal'];\n\n const result: Record<string, any> = { ...payload };\n\n for (const [key, value] of Object.entries(payload)) {\n const columnType = columnTypeMap[key];\n if (!columnType || value === null || value === undefined) continue;\n\n switch (columnType) {\n case 'bigint':\n case 'integer':\n case 'smallint':\n case 'numeric':\n case 'decimal':\n result[key] = Number(value);\n break;\n case 'boolean':\n result[key] = value === 'true' || value === '1';\n break;\n case 'timestamp without time zone':\n case 'timestamp with time zone':\n case 'date':\n result[key] = new Date(value);\n break;\n case 'json':\n case 'jsonb':\n try {\n result[key] = typeof value === 'string' ? JSON.parse(value) : value;\n } catch {\n result[key] = value;\n }\n break;\n default:\n // leave as string\n result[key] = value;\n break;\n }\n }\n\n return result;\n}\n\n// check the modelFields with data exists\nexport const validateModelFieldsWithData = (modelFields: any, data: any) => {\n let resultInvalidFields: string[] = []\n\n let modelFieldKeys = modelFields.map((i: any) => i.name)\n\n Object.keys(data).forEach(i => {\n let check = modelFieldKeys.includes(i)\n if (check === false) {\n resultInvalidFields.push(i)\n }\n })\n\n return resultInvalidFields\n}"]}
|