@autofleet/sadot 1.0.13-beta-3 → 1.0.14
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/README.md +0 -2
- package/dist/api/v1/definition/index.cjs +1 -1
- package/dist/api/v1/definition/index.cjs.map +1 -1
- package/dist/api/v1/definition/index.js +1 -1
- package/dist/api/v1/definition/index.js.map +1 -1
- package/dist/api/v1/definition/validations.cjs.map +1 -1
- package/dist/api/v1/definition/validations.js.map +1 -1
- package/dist/api/v1/errors.cjs +1 -1
- package/dist/api/v1/errors.cjs.map +1 -1
- package/dist/api/v1/errors.js +1 -1
- package/dist/api/v1/errors.js.map +1 -1
- package/dist/api/v1/validator/index.cjs.map +1 -1
- package/dist/api/v1/validator/index.js +1 -1
- package/dist/api/v1/validator/index.js.map +1 -1
- package/dist/errors/index.cjs +2 -2
- package/dist/errors/index.cjs.map +1 -1
- package/dist/errors/index.js +2 -2
- package/dist/errors/index.js.map +1 -1
- package/dist/events/index.cjs +1 -1
- package/dist/events/index.cjs.map +1 -1
- package/dist/events/index.js +1 -1
- package/dist/events/index.js.map +1 -1
- package/dist/hooks/enrich.cjs +1 -1
- package/dist/hooks/enrich.cjs.map +1 -1
- package/dist/hooks/enrich.js +1 -1
- package/dist/hooks/enrich.js.map +1 -1
- package/dist/hooks/find.cjs.map +1 -1
- package/dist/hooks/find.js.map +1 -1
- package/dist/hooks/hooks.cjs +1 -1
- package/dist/hooks/hooks.cjs.map +1 -1
- package/dist/hooks/hooks.js +1 -1
- package/dist/hooks/hooks.js.map +1 -1
- package/dist/hooks/utils/updateInstanceValues.cjs.map +1 -1
- package/dist/hooks/utils/updateInstanceValues.js +1 -1
- package/dist/hooks/utils/updateInstanceValues.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/models/CustomFieldDefinition.cjs +1 -1
- package/dist/models/CustomFieldDefinition.cjs.map +1 -1
- package/dist/models/CustomFieldDefinition.js +1 -1
- package/dist/models/CustomFieldDefinition.js.map +1 -1
- package/dist/models/CustomFieldEntries.cjs +1 -1
- package/dist/models/CustomFieldEntries.cjs.map +1 -1
- package/dist/models/CustomFieldEntries.js +1 -1
- package/dist/models/CustomFieldEntries.js.map +1 -1
- package/dist/models/CustomFieldValue.cjs +1 -1
- package/dist/models/CustomFieldValue.cjs.map +1 -1
- package/dist/models/CustomFieldValue.js +1 -1
- package/dist/models/CustomFieldValue.js.map +1 -1
- package/dist/models/CustomValidator.cjs +1 -1
- package/dist/models/CustomValidator.cjs.map +1 -1
- package/dist/models/CustomValidator.js +1 -1
- package/dist/models/CustomValidator.js.map +1 -1
- package/dist/models/index.cjs.map +1 -1
- package/dist/models/index.js.map +1 -1
- package/dist/models/tests/AssociatedTestModel.cjs +1 -1
- package/dist/models/tests/AssociatedTestModel.cjs.map +1 -1
- package/dist/models/tests/AssociatedTestModel.js +1 -1
- package/dist/models/tests/AssociatedTestModel.js.map +1 -1
- package/dist/models/tests/TestModel.cjs +1 -1
- package/dist/models/tests/TestModel.cjs.map +1 -1
- package/dist/models/tests/TestModel.js +1 -1
- package/dist/models/tests/TestModel.js.map +1 -1
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +1 -1
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +1 -1
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +1 -1
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +1 -1
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +1 -1
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +1 -1
- package/dist/models/tests/contextAwareModels/ContextTestModel.js +1 -1
- package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +1 -1
- package/dist/repository/definition.cjs +1 -1
- package/dist/repository/definition.cjs.map +1 -1
- package/dist/repository/definition.js +1 -1
- package/dist/repository/definition.js.map +1 -1
- package/dist/repository/entries.cjs +1 -1
- package/dist/repository/entries.cjs.map +1 -1
- package/dist/repository/entries.js +1 -1
- package/dist/repository/entries.js.map +1 -1
- package/dist/repository/validator.cjs.map +1 -1
- package/dist/repository/validator.js.map +1 -1
- package/dist/repository/value.cjs +1 -1
- package/dist/repository/value.cjs.map +1 -1
- package/dist/repository/value.js +1 -1
- package/dist/repository/value.js.map +1 -1
- package/dist/scopes/filter.cjs.map +1 -1
- package/dist/scopes/filter.js.map +1 -1
- package/dist/scopes/helpers/filter.helpers.cjs +1 -1
- package/dist/scopes/helpers/filter.helpers.cjs.map +1 -1
- package/dist/scopes/helpers/filter.helpers.d.cts +2 -2
- package/dist/scopes/helpers/filter.helpers.d.ts +2 -2
- package/dist/scopes/helpers/filter.helpers.js +1 -1
- package/dist/scopes/helpers/filter.helpers.js.map +1 -1
- package/dist/types/index.d.cts +6 -6
- package/dist/types/index.d.ts +7 -7
- package/dist/utils/constants/index.cjs.map +1 -1
- package/dist/utils/constants/index.js.map +1 -1
- package/dist/utils/db/index.cjs +1 -1
- package/dist/utils/db/index.cjs.map +1 -1
- package/dist/utils/db/index.js +1 -1
- package/dist/utils/db/index.js.map +1 -1
- package/dist/utils/helpers/index.cjs.map +1 -1
- package/dist/utils/helpers/index.js.map +1 -1
- package/dist/utils/init.cjs +1 -1
- package/dist/utils/init.cjs.map +1 -1
- package/dist/utils/init.js +1 -1
- package/dist/utils/init.js.map +1 -1
- package/dist/utils/logger/index.cjs +1 -1
- package/dist/utils/logger/index.cjs.map +1 -1
- package/dist/utils/logger/index.js +1 -1
- package/dist/utils/logger/index.js.map +1 -1
- package/dist/utils/scopeAttributes.cjs.map +1 -1
- package/dist/utils/scopeAttributes.js.map +1 -1
- package/dist/utils/validations/index.cjs.map +1 -1
- package/dist/utils/validations/index.js.map +1 -1
- package/dist/utils/validations/schema/validator-schema.cjs.map +1 -1
- package/dist/utils/validations/schema/validator-schema.js.map +1 -1
- package/dist/utils/validations/validators/index.cjs.map +1 -1
- package/dist/utils/validations/validators/index.js.map +1 -1
- package/dist/utils/validations/validators/select.validator.cjs.map +1 -1
- package/dist/utils/validations/validators/select.validator.js.map +1 -1
- package/dist/utils/validations/validators/status.validator.cjs.map +1 -1
- package/dist/utils/validations/validators/status.validator.js.map +1 -1
- package/package.json +2 -16
- /package/dist/_virtual/{_@oxc-project_runtime@0.89.0 → _@oxc-project_runtime@0.94.0}/helpers/decorate.cjs +0 -0
- /package/dist/_virtual/{_@oxc-project_runtime@0.89.0 → _@oxc-project_runtime@0.94.0}/helpers/decorate.js +0 -0
- /package/dist/_virtual/{_@oxc-project_runtime@0.89.0 → _@oxc-project_runtime@0.94.0}/helpers/decorateMetadata.cjs +0 -0
- /package/dist/_virtual/{_@oxc-project_runtime@0.89.0 → _@oxc-project_runtime@0.94.0}/helpers/decorateMetadata.js +0 -0
package/README.md
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/logger/index.cjs`),n=require(`../../../repository/definition.cjs`),r=require(`../errors.cjs`),i=require(`./validations.cjs`);let a=require(`@autofleet/errors`);a=e.__toESM(a);let o=require(`@autofleet/node-common`);o=e.__toESM(o);const s=(0,o.Router)({logger:t.default}),c=`CustomFieldDefinition`,l=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());s.post(`/`,async(e,a)=>{let{modelName:o}=e.params,s=l(o);try{let t=await i.validateCustomFieldDefinitionCreation(e.body),r=await n.create({...t,modelType:s});return a.status(201).json(r)}catch(e){return t.default.error(`Failed to create custom field definition`,e),r.default(e,a,{logger:t.default,message:`Error in create ${c} request`})}}),s.get(`/:customFieldDefinitionId`,async(e,i)=>{let{customFieldDefinitionId:o}=e.params;try{let e=await n.findById(o);if(!e)throw new a.ResourceNotFoundError;return i.json(e)}catch(e){return t.default.error(`Failed to fetch custom field definition`,e),r.default(e,i,{logger:t.default,message:`Error in get ${c} request`})}}),s.get(`/`,async(e,i)=>{let{params:{modelName:a},query:{entityIds:o}}=e,s=l(a);try{let e={modelType:s,...o
|
|
1
|
+
const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/logger/index.cjs`),n=require(`../../../repository/definition.cjs`),r=require(`../errors.cjs`),i=require(`./validations.cjs`);let a=require(`@autofleet/errors`);a=e.__toESM(a);let o=require(`@autofleet/node-common`);o=e.__toESM(o);const s=(0,o.Router)({logger:t.default}),c=`CustomFieldDefinition`,l=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());s.post(`/`,async(e,a)=>{let{modelName:o}=e.params,s=l(o);try{let t=await i.validateCustomFieldDefinitionCreation(e.body),r=await n.create({...t,modelType:s});return a.status(201).json(r)}catch(e){return t.default.error(`Failed to create custom field definition`,e),r.default(e,a,{logger:t.default,message:`Error in create ${c} request`})}}),s.get(`/:customFieldDefinitionId`,async(e,i)=>{let{customFieldDefinitionId:o}=e.params;try{let e=await n.findById(o);if(!e)throw new a.ResourceNotFoundError;return i.json(e)}catch(e){return t.default.error(`Failed to fetch custom field definition`,e),r.default(e,i,{logger:t.default,message:`Error in get ${c} request`})}}),s.get(`/`,async(e,i)=>{let{params:{modelName:a},query:{entityIds:o}}=e,s=l(a);try{let e={modelType:s,...o&&o.length>0&&{entityId:o}},t=await n.findAll(e,{withDisabled:!0});return i.json(t)}catch(e){return t.default.error(`Failed to fetch custom field definitions`,e),r.default(e,i,{logger:t.default,message:`Error in get all ${c} request`})}}),s.patch(`/:customFieldDefinitionId`,async(e,o)=>{let{customFieldDefinitionId:s,modelName:u}=e.params,d=l(u);try{let t=await i.validateCustomFieldDefinitionUpdate(e.body);if(!await n.findByWhere({id:s,modelType:d}))throw new a.ResourceNotFoundError;let r=await n.update(s,{...t,modelType:d});return o.status(200).json(r)}catch(e){return t.default.error(`Failed to patch custom field definition`,e),r.default(e,o,{logger:t.default,message:`Error in update ${c} request`})}});var u=s;exports.default=u;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","validateCustomFieldDefinitionCreation","handleError","ResourceNotFoundError","validatedPayload: UpdateCustomFieldDefinition","validateCustomFieldDefinitionUpdate"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","validateCustomFieldDefinitionCreation","handleError","ResourceNotFoundError","validatedPayload: UpdateCustomFieldDefinition","validateCustomFieldDefinitionUpdate"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"0TASA,MAAMA,GAAAA,EAAAA,EAAAA,QAA2C,CAAE,OAAA,EAAA,QAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMC,EAAgD,MAAMC,EAAAA,sCAAsC,EAAI,KAAK,CAErG,EAAwB,MAAA,EAAA,OAA4B,CACxD,GAAG,EACH,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAAoF,4BAA6B,MAAO,EAAK,IAAQ,CAC1I,GAAM,CAAE,2BAA4B,EAAI,OACxC,GAAI,CACF,IAAM,EAAwB,MAAA,EAAA,SAA8B,EAAwB,CAEpF,GAAI,CAAC,EACH,MAAM,IAAIC,EAAAA,sBAGZ,OAAO,EAAI,KAAK,EAAsB,OAC/B,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,gBAAgB,EAAO,UAAW,CAAC,GAE9F,CAKF,EAAO,IAAuF,IAAK,MAAO,EAAK,IAAQ,CACrH,GAAM,CAAE,OAAQ,CAAE,aAAa,MAAO,CAAE,cAAgB,EAElD,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAM,EAAQ,CACZ,YACA,GAAI,GAAa,EAAU,OAAS,GAAK,CAAE,SAAU,EAAW,CACjE,CACK,EAAyB,MAAA,EAAA,QAA6B,EAAO,CAAE,aAAc,GAAM,CAAC,CAC1F,OAAO,EAAI,KAAK,EAAuB,OAChC,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,2CAA4C,EAAI,CACtDA,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,oBAAoB,EAAO,UAAW,CAAC,GAElG,CAKF,EAAO,MAAsF,4BAA6B,MAAO,EAAK,IAAQ,CAC5I,GAAM,CAAE,0BAAyB,aAAc,EAAI,OAC7C,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAME,EAAgD,MAAMC,EAAAA,oCAAoC,EAAI,KAAK,CAOzG,GAAI,CAL0B,MAAA,EAAA,YAAiC,CAC7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAIF,EAAAA,sBAGZ,IAAM,EAA+B,MAAA,EAAA,OACnC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../../../utils/logger/index.js";import{create as t,findAll as n,findById as r,findByWhere as i,update as a}from"../../../repository/definition.js";import o from"../errors.js";import{validateCustomFieldDefinitionCreation as s,validateCustomFieldDefinitionUpdate as c}from"./validations.js";import{ResourceNotFoundError as l}from"@autofleet/errors";import{Router as u}from"@autofleet/node-common";const d=u({logger:e}),f=`CustomFieldDefinition`,p=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());d.post(`/`,async(n,r)=>{let{modelName:i}=n.params,a=p(i);try{let e=await s(n.body),
|
|
1
|
+
import e from"../../../utils/logger/index.js";import{create as t,findAll as n,findById as r,findByWhere as i,update as a}from"../../../repository/definition.js";import o from"../errors.js";import{validateCustomFieldDefinitionCreation as s,validateCustomFieldDefinitionUpdate as c}from"./validations.js";import{ResourceNotFoundError as l}from"@autofleet/errors";import{Router as u}from"@autofleet/node-common";const d=u({logger:e}),f=`CustomFieldDefinition`,p=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());d.post(`/`,async(n,r)=>{let{modelName:i}=n.params,a=p(i);try{let e=await t({...await s(n.body),modelType:a});return r.status(201).json(e)}catch(t){return e.error(`Failed to create custom field definition`,t),o(t,r,{logger:e,message:`Error in create ${f} request`})}}),d.get(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:i}=t.params;try{let e=await r(i);if(!e)throw new l;return n.json(e)}catch(t){return e.error(`Failed to fetch custom field definition`,t),o(t,n,{logger:e,message:`Error in get ${f} request`})}}),d.get(`/`,async(t,r)=>{let{params:{modelName:i},query:{entityIds:a}}=t,s=p(i);try{let e=await n({modelType:s,...a&&a.length>0&&{entityId:a}},{withDisabled:!0});return r.json(e)}catch(t){return e.error(`Failed to fetch custom field definitions`,t),o(t,r,{logger:e,message:`Error in get all ${f} request`})}}),d.patch(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:r,modelName:s}=t.params,u=p(s);try{let e=await c(t.body);if(!await i({id:r,modelType:u}))throw new l;let o=await a(r,{...e,modelType:u});return n.status(200).json(o)}catch(t){return e.error(`Failed to patch custom field definition`,t),o(t,n,{logger:e,message:`Error in update ${f} request`})}});var m=d;export{m as default};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","DefinitionRepo.create","handleError","DefinitionRepo.findById","DefinitionRepo.findAll","validatedPayload: UpdateCustomFieldDefinition","DefinitionRepo.findByWhere","DefinitionRepo.update"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g,
|
|
1
|
+
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","DefinitionRepo.create","handleError","DefinitionRepo.findById","DefinitionRepo.findAll","validatedPayload: UpdateCustomFieldDefinition","DefinitionRepo.findByWhere","DefinitionRepo.update"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"yZASA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CAGF,IAAM,EAAwB,MAAME,EAAsB,CACxD,GAHoD,MAAM,EAAsC,EAAI,KAAK,CAIzG,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAAoF,4BAA6B,MAAO,EAAK,IAAQ,CAC1I,GAAM,CAAE,2BAA4B,EAAI,OACxC,GAAI,CACF,IAAM,EAAwB,MAAMC,EAAwB,EAAwB,CAEpF,GAAI,CAAC,EACH,MAAM,IAAI,EAGZ,OAAO,EAAI,KAAK,EAAsB,OAC/B,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,gBAAgB,EAAO,UAAW,CAAC,GAE9F,CAKF,EAAO,IAAuF,IAAK,MAAO,EAAK,IAAQ,CACrH,GAAM,CAAE,OAAQ,CAAE,aAAa,MAAO,CAAE,cAAgB,EAElD,EAAY,EAAa,EAAU,CACzC,GAAI,CAKF,IAAM,EAAyB,MAAME,EAJvB,CACZ,YACA,GAAI,GAAa,EAAU,OAAS,GAAK,CAAE,SAAU,EAAW,CACjE,CACkE,CAAE,aAAc,GAAM,CAAC,CAC1F,OAAO,EAAI,KAAK,EAAuB,OAChC,EAAK,CAEZ,OADA,EAAO,MAAM,2CAA4C,EAAI,CACtDF,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,oBAAoB,EAAO,UAAW,CAAC,GAElG,CAKF,EAAO,MAAsF,4BAA6B,MAAO,EAAK,IAAQ,CAC5I,GAAM,CAAE,0BAAyB,aAAc,EAAI,OAC7C,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMG,EAAgD,MAAM,EAAoC,EAAI,KAAK,CAOzG,GAAI,CAL0B,MAAMC,EAA2B,CAC7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAI,EAGZ,IAAM,EAA+B,MAAMC,EACzC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDL,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validations.cjs","names":["Joi","CustomFieldDefinitionType"],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"validations.cjs","names":["Joi","CustomFieldDefinitionType"],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"8IAIA,MAAM,EAAuBA,EAAAA,QAAI,OAAO,CACtC,KAAMA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC7B,KAAMA,EAAAA,QAAI,QAAQ,CAClB,KAAMA,EAAAA,QAAI,QAAQ,CAClB,QAASA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyBA,EAAAA,QAAI,OAAO,CACxC,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC9B,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAUI,EAAmBA,EAAAA,QAAI,KAAK,YAAa,CAC7C,GAAIC,EAAAA,0BAA0B,OAC9B,KAAMD,EAAAA,QAAI,OAAO,CAAC,UAAU,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC,QAAQ,CAChE,UAAWA,EAAAA,QAAI,KAAK,YAAa,CAC/B,GAAIC,EAAAA,0BAA0B,OAC9B,KAAMD,EAAAA,QAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAuB,CAAC,IAAI,EAAE,CAAC,OAAO,QA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AG,OAAO,OAAOC,EAAAA,0BAA0B,CAAC,CAAC,UAAU,CACrF,SAAUD,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,CACxC,WAAYA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CACnC,YAAaA,EAAAA,QAAI,QAAQ,CACzB,SAAUA,EAAAA,QAAI,SAAS,CACvB,SAAUA,EAAAA,QAAI,SAAS,CACvB,mBAAoBA,EAAAA,QAAI,SAAS,CAClC,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAE3E,EAAoCA,EAAAA,QAAI,OAAO,CACnD,YAAaA,EAAAA,QAAI,QAAQ,CACzB,WAAY,EACZ,aAAc,EACd,UAAWA,EAAAA,QAAI,QAAQ,CAAC,MAAM,GAAG,OAAO,OAAOC,EAAAA,0BAA0B,CAAC,CAC1E,YAAaD,EAAAA,QAAI,QAAQ,CAAC,MAAM,KAAK,CACrC,SAAUA,EAAAA,QAAI,SAAS,CACvB,SAAUA,EAAAA,QAAI,SAAS,CACvB,mBAAoBA,EAAAA,QAAI,SAAS,CAClC,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAEpE,EAAyC,GACpD,EAAoC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC,CAEtE,EAAuC,GAClD,EAAkC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validations.js","names":[],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"validations.js","names":[],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"iGAIA,MAAM,EAAuB,EAAI,OAAO,CACtC,KAAM,EAAI,QAAQ,CAAC,UAAU,CAC7B,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CAClB,QAAS,EAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyB,EAAI,OAAO,CACxC,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC9B,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAUI,EAAmB,EAAI,KAAK,YAAa,CAC7C,GAAI,EAA0B,OAC9B,KAAM,EAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAI,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC,QAAQ,CAChE,UAAW,EAAI,KAAK,YAAa,CAC/B,GAAI,EAA0B,OAC9B,KAAM,EAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAuB,CAAC,IAAI,EAAE,CAAC,OAAO,QAAQ,CACjF,UAAW,EAAI,WAAW,CAC3B,CAAC,CACH,CAAC,CAEI,EAAqB,EAAI,KAAK,YAAa,CAC/C,OAAQ,CACN,CAAE,GAAI,EAA0B,QAAS,KAAM,EAAI,SAAS,CAAC,MAAM,KAAK,CAAE,C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,QAAQ,CAAC,MAAM,GAAG,OAAO,OAAO,EAA0B,CAAC,CAC1E,YAAa,EAAI,QAAQ,CAAC,MAAM,KAAK,CACrC,SAAU,EAAI,SAAS,CACvB,SAAU,EAAI,SAAS,CACvB,mBAAoB,EAAI,SAAS,CAClC,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAEpE,EAAyC,GACpD,EAAoC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC,CAEtE,EAAuC,GAClD,EAAkC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC"}
|
package/dist/api/v1/errors.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../../_virtual/rolldown_runtime.cjs`);let t=require(`sequelize`);t=e.__toESM(t);let n=require(`joi`);n=e.__toESM(n);let r=require(`@autofleet/errors`);r=e.__toESM(r);var i=(e,i,a
|
|
1
|
+
const e=require(`../../_virtual/rolldown_runtime.cjs`);let t=require(`sequelize`);t=e.__toESM(t);let n=require(`joi`);n=e.__toESM(n);let r=require(`@autofleet/errors`);r=e.__toESM(r);var i=(e,i,a)=>{let o=e;return[n.ValidationError,t.ValidationError].some(t=>e instanceof t)&&(o=new r.BadRequest([e])),(0,r.handleError)(o,i,a)};exports.default=i;
|
|
2
2
|
//# sourceMappingURL=errors.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":["InputValidationError","DatabaseValidationError","BadRequest"],"sources":["../../../src/api/v1/errors.ts"],"sourcesContent":["import type { Response } from 'express';\nimport { handleError, BadRequest, type LogPayload } from '@autofleet/errors';\nimport { ValidationError as InputValidationError } from 'joi';\nimport { ValidationError as DatabaseValidationError } from 'sequelize';\n\nexport default (err: Error, res: Response, additionalData: LogPayload
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":["InputValidationError","DatabaseValidationError","BadRequest"],"sources":["../../../src/api/v1/errors.ts"],"sourcesContent":["import type { Response } from 'express';\nimport { handleError, BadRequest, type LogPayload } from '@autofleet/errors';\nimport { ValidationError as InputValidationError } from 'joi';\nimport { ValidationError as DatabaseValidationError } from 'sequelize';\n\nexport default (err: Error, res: Response, additionalData: LogPayload): void => {\n let error = err;\n if ([InputValidationError, DatabaseValidationError].some(ErrClass => err instanceof ErrClass)) {\n error = new BadRequest([err]);\n }\n\n return handleError(error, res, additionalData);\n};\n"],"mappings":"uLAKA,IAAA,GAAgB,EAAY,EAAe,IAAqC,CAC9E,IAAI,EAAQ,EAKZ,MAJI,CAACA,EAAAA,gBAAsBC,EAAAA,gBAAwB,CAAC,KAAK,GAAY,aAAe,EAAS,GAC3F,EAAQ,IAAIC,EAAAA,WAAW,CAAC,EAAI,CAAC,GAG/B,EAAA,EAAA,aAAmB,EAAO,EAAK,EAAe"}
|
package/dist/api/v1/errors.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ValidationError as e}from"sequelize";import{ValidationError as t}from"joi";import{BadRequest as n,handleError as r}from"@autofleet/errors";var i=(i,a,o
|
|
1
|
+
import{ValidationError as e}from"sequelize";import{ValidationError as t}from"joi";import{BadRequest as n,handleError as r}from"@autofleet/errors";var i=(i,a,o)=>{let s=i;return[t,e].some(e=>i instanceof e)&&(s=new n([i])),r(s,a,o)};export{i as default};
|
|
2
2
|
//# sourceMappingURL=errors.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["InputValidationError","DatabaseValidationError"],"sources":["../../../src/api/v1/errors.ts"],"sourcesContent":["import type { Response } from 'express';\nimport { handleError, BadRequest, type LogPayload } from '@autofleet/errors';\nimport { ValidationError as InputValidationError } from 'joi';\nimport { ValidationError as DatabaseValidationError } from 'sequelize';\n\nexport default (err: Error, res: Response, additionalData: LogPayload
|
|
1
|
+
{"version":3,"file":"errors.js","names":["InputValidationError","DatabaseValidationError"],"sources":["../../../src/api/v1/errors.ts"],"sourcesContent":["import type { Response } from 'express';\nimport { handleError, BadRequest, type LogPayload } from '@autofleet/errors';\nimport { ValidationError as InputValidationError } from 'joi';\nimport { ValidationError as DatabaseValidationError } from 'sequelize';\n\nexport default (err: Error, res: Response, additionalData: LogPayload): void => {\n let error = err;\n if ([InputValidationError, DatabaseValidationError].some(ErrClass => err instanceof ErrClass)) {\n error = new BadRequest([err]);\n }\n\n return handleError(error, res, additionalData);\n};\n"],"mappings":"kJAKA,IAAA,GAAgB,EAAY,EAAe,IAAqC,CAC9E,IAAI,EAAQ,EAKZ,MAJI,CAACA,EAAsBC,EAAwB,CAAC,KAAK,GAAY,aAAe,EAAS,GAC3F,EAAQ,IAAI,EAAW,CAAC,EAAI,CAAC,EAGxB,EAAY,EAAO,EAAK,EAAe"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validations","StatusCodes","handleError","ResourceNotFoundError"],"sources":["../../../../src/api/v1/validator/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport { StatusCodes } from 'http-status-codes';\nimport handleError from '../errors';\nimport * as ValidatorRepo from '../../../repository/validator';\nimport validations from './validations';\nimport logger from '../../../utils/logger';\nimport { validateValidatorSchema } from '../../../utils/validations/schema/validator-schema';\nimport type { CustomValidator } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomValidator';\n\n/**\n * Create\n */\nrouter.post<{ modelName: string }>('/', async (req, res) => {\n const { modelName } = req.params;\n try {\n // Validate the request body\n const validatedPayload = await validations.create.validateAsync(req.body);\n\n // Validate that the schema is a valid AJV schema\n validateValidatorSchema(validatedPayload.schema);\n\n const validator = await ValidatorRepo.create({\n ...validatedPayload,\n modelType: modelName,\n });\n\n return res.status(StatusCodes.CREATED).json(validator);\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<\n { modelName: string },\n { validators: CustomValidator[] },\n never,\n { entityId?: string; entityType?: string }\n>('/', async (req, res) => {\n try {\n const { modelName } = req.params;\n const { entityId, entityType } = req.query;\n\n const where = {\n modelType: modelName,\n ...(entityId && { entityId }),\n ...(entityType && { entityType }),\n };\n\n const validators = await ValidatorRepo.findAll(where);\n\n return res.status(StatusCodes.OK).json({ validators });\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; validatorId: string }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId, modelName } = req.params;\n // Include disabled validators when fetching by ID\n const validators = await ValidatorRepo.findAll({ id: validatorId, modelType: modelName }, { withDisabled: true });\n\n if (!validators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; validatorId: string }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // Validate the request body\n const validatedPayload = await validations.update.validateAsync(req.body);\n\n // If schema is included in the update, validate that it's a valid AJV schema\n if (validatedPayload.schema) {\n validateValidatorSchema(validatedPayload.schema);\n }\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count, validators] = await ValidatorRepo.update(validatorId, validatedPayload as any);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\n/**\n * Delete (disable)\n */\nrouter.delete<{ modelName: string; validatorId: string }>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count] = await ValidatorRepo.disable(validatorId);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator failed to be disabled');\n }\n\n return res.status(StatusCodes.NO_CONTENT).send();\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in delete ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"+aAUA,MAAMA,GAAAA,EAAAA,EAAAA,QAA2C,CAAE,OAAA,EAAA,QAAQ,CAAC,CACtD,EAAS,kBAKf,EAAO,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validations","StatusCodes","handleError","ResourceNotFoundError"],"sources":["../../../../src/api/v1/validator/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport { StatusCodes } from 'http-status-codes';\nimport handleError from '../errors';\nimport * as ValidatorRepo from '../../../repository/validator';\nimport validations from './validations';\nimport logger from '../../../utils/logger';\nimport { validateValidatorSchema } from '../../../utils/validations/schema/validator-schema';\nimport type { CustomValidator } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomValidator';\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n try {\n // Validate the request body\n const validatedPayload = await validations.create.validateAsync(req.body);\n\n // Validate that the schema is a valid AJV schema\n validateValidatorSchema(validatedPayload.schema);\n\n const validator = await ValidatorRepo.create({\n ...validatedPayload,\n modelType: modelName,\n });\n\n return res.status(StatusCodes.CREATED).json(validator);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<\n { modelName: string; },\n { validators: CustomValidator[]; },\n never,\n { entityId?: string; entityType?: string; }\n>('/', async (req, res) => {\n try {\n const { modelName } = req.params;\n const { entityId, entityType } = req.query;\n\n const where = {\n modelType: modelName,\n ...(entityId && { entityId }),\n ...(entityType && { entityType }),\n };\n\n const validators = await ValidatorRepo.findAll(where);\n\n return res.status(StatusCodes.OK).json({ validators });\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; validatorId: string; }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId, modelName } = req.params;\n // Include disabled validators when fetching by ID\n const validators = await ValidatorRepo.findAll({ id: validatorId, modelType: modelName }, { withDisabled: true });\n\n if (!validators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; validatorId: string; }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // Validate the request body\n const validatedPayload = await validations.update.validateAsync(req.body);\n\n // If schema is included in the update, validate that it's a valid AJV schema\n if (validatedPayload.schema) {\n validateValidatorSchema(validatedPayload.schema);\n }\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count, validators] = await ValidatorRepo.update(validatorId, validatedPayload as any);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\n/**\n * Delete (disable)\n */\nrouter.delete<{ modelName: string; validatorId: string; }>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count] = await ValidatorRepo.disable(validatorId);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator failed to be disabled');\n }\n\n return res.status(StatusCodes.NO_CONTENT).send();\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in delete ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"+aAUA,MAAMA,GAAAA,EAAAA,EAAAA,QAA2C,CAAE,OAAA,EAAA,QAAQ,CAAC,CACtD,EAAS,kBAKf,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OAC1B,GAAI,CAEF,IAAM,EAAmB,MAAMC,EAAAA,QAAY,OAAO,cAAc,EAAI,KAAK,CAGzE,EAAA,wBAAwB,EAAiB,OAAO,CAEhD,IAAM,EAAY,MAAA,EAAA,OAA2B,CAC3C,GAAG,EACH,UAAW,EACZ,CAAC,CAEF,OAAO,EAAI,OAAOC,EAAAA,YAAY,QAAQ,CAAC,KAAK,EAAU,OAC/C,EAAK,CACZ,OAAOC,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAKL,IAAK,MAAO,EAAK,IAAQ,CACzB,GAAI,CACF,GAAM,CAAE,aAAc,EAAI,OACpB,CAAE,WAAU,cAAe,EAAI,MAE/B,EAAQ,CACZ,UAAW,EACX,GAAI,GAAY,CAAE,WAAU,CAC5B,GAAI,GAAc,CAAE,aAAY,CACjC,CAEK,EAAa,MAAA,EAAA,QAA4B,EAAM,CAErD,OAAO,EAAI,OAAOD,EAAAA,YAAY,GAAG,CAAC,KAAK,CAAE,aAAY,CAAC,OAC/C,EAAK,CACZ,OAAOC,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,oBAAoB,EAAO,UAAW,CAAC,GAElG,CAKF,EAAO,IAAkE,gBAAiB,MAAO,EAAK,IAAQ,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M,IAAIC,EAAAA,sBAAsB,sBAAsB,CAGxD,GAAM,CAAC,GAAS,MAAA,EAAA,QAA4B,EAAY,CAExD,GAAI,CAAC,EACH,MAAM,IAAIA,EAAAA,sBAAsB,kCAAkC,CAGpE,OAAO,EAAI,OAAOF,EAAAA,YAAY,WAAW,CAAC,MAAM,OACzC,EAAK,CACZ,OAAOC,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../../../utils/logger/index.js";import t from"../errors.js";import{create as n,disable as r,findAll as i,update as a}from"../../../repository/validator.js";import o from"./validations.js";import{validateValidatorSchema as s}from"../../../utils/validations/schema/validator-schema.js";import{ResourceNotFoundError as c}from"@autofleet/errors";import{Router as l}from"@autofleet/node-common";import{StatusCodes as u}from"http-status-codes";const d=l({logger:e}),f=`CustomValidator`;d.post(`/`,async(r,i)=>{let{modelName:a}=r.params;try{let e=await o.create.validateAsync(r.body);s(e.schema);let t=await n({...e,modelType:a});return i.status(u.CREATED).json(t)}catch(n){return t(n,i,{logger:e,message:`Error in create ${f} request`})}}),d.get(`/`,async(n,r)=>{try{let{modelName:e}=n.params,{entityId:t,entityType:a}=n.query,o={modelType:e,...t&&{entityId:t},...a&&{entityType:a}}
|
|
1
|
+
import e from"../../../utils/logger/index.js";import t from"../errors.js";import{create as n,disable as r,findAll as i,update as a}from"../../../repository/validator.js";import o from"./validations.js";import{validateValidatorSchema as s}from"../../../utils/validations/schema/validator-schema.js";import{ResourceNotFoundError as c}from"@autofleet/errors";import{Router as l}from"@autofleet/node-common";import{StatusCodes as u}from"http-status-codes";const d=l({logger:e}),f=`CustomValidator`;d.post(`/`,async(r,i)=>{let{modelName:a}=r.params;try{let e=await o.create.validateAsync(r.body);s(e.schema);let t=await n({...e,modelType:a});return i.status(u.CREATED).json(t)}catch(n){return t(n,i,{logger:e,message:`Error in create ${f} request`})}}),d.get(`/`,async(n,r)=>{try{let{modelName:e}=n.params,{entityId:t,entityType:a}=n.query,o=await i({modelType:e,...t&&{entityId:t},...a&&{entityType:a}});return r.status(u.OK).json({validators:o})}catch(n){return t(n,r,{logger:e,message:`Error in get all ${f} request`})}}),d.get(`/:validatorId`,async(n,r)=>{try{let{validatorId:e,modelName:t}=n.params,a=await i({id:e,modelType:t},{withDisabled:!0});if(!a.length)throw new c(`Validator not found`);return r.status(u.OK).json(a[0])}catch(n){return t(n,r,{logger:e,message:`Error in get ${f} request`})}}),d.patch(`/:validatorId`,async(n,r)=>{try{let{validatorId:e}=n.params,t=await o.update.validateAsync(n.body);if(t.schema&&s(t.schema),!(await i({id:e},{withDisabled:!0})).length)throw new c(`Validator not found`);let[l,d]=await a(e,t);if(!l)throw new c(`Validator not found`);return r.status(u.OK).json(d[0])}catch(n){return t(n,r,{logger:e,message:`Error in update ${f} request`})}}),d.delete(`/:validatorId`,async(n,a)=>{try{let{validatorId:e}=n.params;if(!(await i({id:e},{withDisabled:!0})).length)throw new c(`Validator not found`);let[t]=await r(e);if(!t)throw new c(`Validator failed to be disabled`);return a.status(u.NO_CONTENT).send()}catch(n){return t(n,a,{logger:e,message:`Error in delete ${f} request`})}});var p=d;export{p as default};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validations","ValidatorRepo.create","handleError","ValidatorRepo.findAll","ValidatorRepo.update","ValidatorRepo.disable"],"sources":["../../../../src/api/v1/validator/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport { StatusCodes } from 'http-status-codes';\nimport handleError from '../errors';\nimport * as ValidatorRepo from '../../../repository/validator';\nimport validations from './validations';\nimport logger from '../../../utils/logger';\nimport { validateValidatorSchema } from '../../../utils/validations/schema/validator-schema';\nimport type { CustomValidator } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomValidator';\n\n/**\n * Create\n */\nrouter.post<{ modelName: string }>('/', async (req, res) => {\n const { modelName } = req.params;\n try {\n // Validate the request body\n const validatedPayload = await validations.create.validateAsync(req.body);\n\n // Validate that the schema is a valid AJV schema\n validateValidatorSchema(validatedPayload.schema);\n\n const validator = await ValidatorRepo.create({\n ...validatedPayload,\n modelType: modelName,\n });\n\n return res.status(StatusCodes.CREATED).json(validator);\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<\n { modelName: string },\n { validators: CustomValidator[] },\n never,\n { entityId?: string; entityType?: string }\n>('/', async (req, res) => {\n try {\n const { modelName } = req.params;\n const { entityId, entityType } = req.query;\n\n const where = {\n modelType: modelName,\n ...(entityId && { entityId }),\n ...(entityType && { entityType }),\n };\n\n const validators = await ValidatorRepo.findAll(where);\n\n return res.status(StatusCodes.OK).json({ validators });\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; validatorId: string }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId, modelName } = req.params;\n // Include disabled validators when fetching by ID\n const validators = await ValidatorRepo.findAll({ id: validatorId, modelType: modelName }, { withDisabled: true });\n\n if (!validators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; validatorId: string }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // Validate the request body\n const validatedPayload = await validations.update.validateAsync(req.body);\n\n // If schema is included in the update, validate that it's a valid AJV schema\n if (validatedPayload.schema) {\n validateValidatorSchema(validatedPayload.schema);\n }\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count, validators] = await ValidatorRepo.update(validatorId, validatedPayload as any);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\n/**\n * Delete (disable)\n */\nrouter.delete<{ modelName: string; validatorId: string }>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count] = await ValidatorRepo.disable(validatorId);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator failed to be disabled');\n }\n\n return res.status(StatusCodes.NO_CONTENT).send();\n } catch (err) {\n return handleError(err, res, { logger, message: `Error in delete ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"ocAUA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CACtD,EAAS,kBAKf,EAAO,
|
|
1
|
+
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validations","ValidatorRepo.create","handleError","ValidatorRepo.findAll","ValidatorRepo.update","ValidatorRepo.disable"],"sources":["../../../../src/api/v1/validator/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport { StatusCodes } from 'http-status-codes';\nimport handleError from '../errors';\nimport * as ValidatorRepo from '../../../repository/validator';\nimport validations from './validations';\nimport logger from '../../../utils/logger';\nimport { validateValidatorSchema } from '../../../utils/validations/schema/validator-schema';\nimport type { CustomValidator } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomValidator';\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n try {\n // Validate the request body\n const validatedPayload = await validations.create.validateAsync(req.body);\n\n // Validate that the schema is a valid AJV schema\n validateValidatorSchema(validatedPayload.schema);\n\n const validator = await ValidatorRepo.create({\n ...validatedPayload,\n modelType: modelName,\n });\n\n return res.status(StatusCodes.CREATED).json(validator);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<\n { modelName: string; },\n { validators: CustomValidator[]; },\n never,\n { entityId?: string; entityType?: string; }\n>('/', async (req, res) => {\n try {\n const { modelName } = req.params;\n const { entityId, entityType } = req.query;\n\n const where = {\n modelType: modelName,\n ...(entityId && { entityId }),\n ...(entityType && { entityType }),\n };\n\n const validators = await ValidatorRepo.findAll(where);\n\n return res.status(StatusCodes.OK).json({ validators });\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; validatorId: string; }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId, modelName } = req.params;\n // Include disabled validators when fetching by ID\n const validators = await ValidatorRepo.findAll({ id: validatorId, modelType: modelName }, { withDisabled: true });\n\n if (!validators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; validatorId: string; }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // Validate the request body\n const validatedPayload = await validations.update.validateAsync(req.body);\n\n // If schema is included in the update, validate that it's a valid AJV schema\n if (validatedPayload.schema) {\n validateValidatorSchema(validatedPayload.schema);\n }\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count, validators] = await ValidatorRepo.update(validatorId, validatedPayload as any);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\n/**\n * Delete (disable)\n */\nrouter.delete<{ modelName: string; validatorId: string; }>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count] = await ValidatorRepo.disable(validatorId);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator failed to be disabled');\n }\n\n return res.status(StatusCodes.NO_CONTENT).send();\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in delete ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"ocAUA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CACtD,EAAS,kBAKf,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OAC1B,GAAI,CAEF,IAAM,EAAmB,MAAMC,EAAY,OAAO,cAAc,EAAI,KAAK,CAGzE,EAAwB,EAAiB,OAAO,CAEhD,IAAM,EAAY,MAAMC,EAAqB,CAC3C,GAAG,EACH,UAAW,EACZ,CAAC,CAEF,OAAO,EAAI,OAAO,EAAY,QAAQ,CAAC,KAAK,EAAU,OAC/C,EAAK,CACZ,OAAOC,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAKL,IAAK,MAAO,EAAK,IAAQ,CACzB,GAAI,CACF,GAAM,CAAE,aAAc,EAAI,OACpB,CAAE,WAAU,cAAe,EAAI,MAQ/B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EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,OAAoD,gBAAiB,MAAO,EAAK,IAAQ,CAC9F,GAAI,CACF,GAAM,CAAE,eAAgB,EAAI,OAI5B,GAAI,EADuB,MAAMC,EAAsB,CAAE,GAAI,EAAa,CAAE,CAAE,aAAc,GAAM,CAAC,EAC3E,OACtB,MAAM,IAAI,EAAsB,sBAAsB,CAGxD,GAAM,CAAC,GAAS,MAAME,EAAsB,EAAY,CAExD,GAAI,CAAC,EACH,MAAM,IAAI,EAAsB,kCAAkC,CAGpE,OAAO,EAAI,OAAO,EAAY,WAAW,CAAC,MAAM,OACzC,EAAK,CACZ,OAAOH,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
package/dist/errors/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
const e=require(`../_virtual/rolldown_runtime.cjs`);let t=require(`@autofleet/errors`);t=e.__toESM(t);var n=class extends t.BadRequest{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],
|
|
2
|
-
`)}`}},c=class extends t.BadRequest{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],
|
|
1
|
+
const e=require(`../_virtual/rolldown_runtime.cjs`);let t=require(`@autofleet/errors`);t=e.__toESM(t);var n=class extends t.BadRequest{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],void 0,e),this.message=`MISSING_REQUIRED_CUSTOM_FIELDS`}},r=class extends t.BadRequest{constructor(e){let t=Error(`Type "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_FIELD_TYPE`}},i=class extends t.BadRequest{constructor(e){let t=Error(`Validation for "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_VALIDATION_TYPE`}},a=class extends t.BadRequest{constructor(e){let t=Error(`Invalid field type ${e}`);super([t],void 0,null),this.message=`INVALID_FIELD_TYPE`}},o=class extends t.BadRequest{constructor(e,t,n){let r=`Invalid Value on field '${t}'. ${n.message.replace(/"/g,``).replace(`value`,`'${t}'`)}. received: '${typeof e==`object`?JSON.stringify(e):e}'`;super([Error(r)],void 0,null),this.message=r}},s=class extends t.BadRequest{constructor(e,t){let n=t.map(e=>new o(e.value,e.fieldDefinitionName,e.joiValidationError));super(n,void 0,null),this.message=`Invalid entries on ${e}\n${t.map(e=>`${e.fieldDefinitionName} - ${e.joiValidationError.message}`).join(`
|
|
2
|
+
`)}`}},c=class extends t.BadRequest{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],void 0,null),this.message=`MISSING_DEFINITION`}};exports.InvalidEntriesError=s,exports.InvalidFieldTypeError=a,exports.InvalidValueError=o,exports.MissingDefinitionError=c,exports.MissingRequiredCustomFieldError=n,exports.UnsupportedCustomFieldTypeError=r,exports.UnsupportedCustomValidationError=i;
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["BadRequest"],"sources":["../../src/errors/index.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["BadRequest"],"sources":["../../src/errors/index.ts"],"sourcesContent":["import { BadRequest } from '@autofleet/errors';\nimport type { ValidationError } from 'joi';\nimport type { EntriesValidationError } from '../types/entries';\n\nexport class MissingRequiredCustomFieldError extends BadRequest {\n constructor(missingFields: string[]) {\n const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);\n super([err], undefined, missingFields);\n this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';\n }\n}\n\nexport class UnsupportedCustomFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Type \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';\n }\n}\n\nexport class UnsupportedCustomValidationError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Validation for \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';\n }\n}\n\nexport class InvalidFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Invalid field type ${fieldType}`);\n super([err], undefined, null);\n this.message = 'INVALID_FIELD_TYPE';\n }\n}\n\nexport class InvalidValueError extends BadRequest {\n constructor(value: any, fieldDefinitionName: string, joiValidationError: ValidationError) {\n const formattedErrorMessage = joiValidationError.message\n .replace(/\"/g, '')\n .replace('value', `'${fieldDefinitionName}'`);\n\n const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;\n\n const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;\n\n const err = new Error(invalidValueMessage);\n super([err], undefined, null);\n this.message = invalidValueMessage;\n }\n}\n\nexport class InvalidEntriesError extends BadRequest {\n constructor(modelId: string, validationErrors: EntriesValidationError[]) {\n const errors = validationErrors.map(validationError => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));\n super(errors, undefined, null);\n this.message = `Invalid entries on ${modelId}\\n${validationErrors.map(validationError => (\n `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`\n )).join('\\n')}`;\n }\n}\n\nexport class MissingDefinitionError extends BadRequest {\n constructor(fieldNames: string[]) {\n const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);\n super([err], undefined, null);\n this.message = 'MISSING_DEFINITION';\n }\n}\n"],"mappings":"sGAIA,IAAa,EAAb,cAAqDA,EAAAA,UAAW,CAC9D,YAAY,EAAyB,CACnC,IAAM,EAAU,MAAM,6CAA6C,EAAc,KAAK,IAAI,GAAG,CAC7F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,EAAc,CACtC,KAAK,QAAU,mCAIN,EAAb,cAAqDA,EAAAA,UAAW,CAC9D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,SAAS,EA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AC7B,KAAK,QAAU"}
|
package/dist/errors/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{BadRequest as e}from"@autofleet/errors";var t=class extends e{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],
|
|
2
|
-
`)}`}},s=class extends e{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],
|
|
1
|
+
import{BadRequest as e}from"@autofleet/errors";var t=class extends e{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],void 0,e),this.message=`MISSING_REQUIRED_CUSTOM_FIELDS`}},n=class extends e{constructor(e){let t=Error(`Type "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_FIELD_TYPE`}},r=class extends e{constructor(e){let t=Error(`Validation for "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_VALIDATION_TYPE`}},i=class extends e{constructor(e){let t=Error(`Invalid field type ${e}`);super([t],void 0,null),this.message=`INVALID_FIELD_TYPE`}},a=class extends e{constructor(e,t,n){let r=`Invalid Value on field '${t}'. ${n.message.replace(/"/g,``).replace(`value`,`'${t}'`)}. received: '${typeof e==`object`?JSON.stringify(e):e}'`;super([Error(r)],void 0,null),this.message=r}},o=class extends e{constructor(e,t){let n=t.map(e=>new a(e.value,e.fieldDefinitionName,e.joiValidationError));super(n,void 0,null),this.message=`Invalid entries on ${e}\n${t.map(e=>`${e.fieldDefinitionName} - ${e.joiValidationError.message}`).join(`
|
|
2
|
+
`)}`}},s=class extends e{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],void 0,null),this.message=`MISSING_DEFINITION`}};export{o as InvalidEntriesError,i as InvalidFieldTypeError,a as InvalidValueError,s as MissingDefinitionError,t as MissingRequiredCustomFieldError,n as UnsupportedCustomFieldTypeError,r as UnsupportedCustomValidationError};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/errors/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/errors/index.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/errors/index.ts"],"sourcesContent":["import { BadRequest } from '@autofleet/errors';\nimport type { ValidationError } from 'joi';\nimport type { EntriesValidationError } from '../types/entries';\n\nexport class MissingRequiredCustomFieldError extends BadRequest {\n constructor(missingFields: string[]) {\n const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);\n super([err], undefined, missingFields);\n this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';\n }\n}\n\nexport class UnsupportedCustomFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Type \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';\n }\n}\n\nexport class UnsupportedCustomValidationError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Validation for \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';\n }\n}\n\nexport class InvalidFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Invalid field type ${fieldType}`);\n super([err], undefined, null);\n this.message = 'INVALID_FIELD_TYPE';\n }\n}\n\nexport class InvalidValueError extends BadRequest {\n constructor(value: any, fieldDefinitionName: string, joiValidationError: ValidationError) {\n const formattedErrorMessage = joiValidationError.message\n .replace(/\"/g, '')\n .replace('value', `'${fieldDefinitionName}'`);\n\n const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;\n\n const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;\n\n const err = new Error(invalidValueMessage);\n super([err], undefined, null);\n this.message = invalidValueMessage;\n }\n}\n\nexport class InvalidEntriesError extends BadRequest {\n constructor(modelId: string, validationErrors: EntriesValidationError[]) {\n const errors = validationErrors.map(validationError => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));\n super(errors, undefined, null);\n this.message = `Invalid entries on ${modelId}\\n${validationErrors.map(validationError => (\n `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`\n )).join('\\n')}`;\n }\n}\n\nexport class MissingDefinitionError extends BadRequest {\n constructor(fieldNames: string[]) {\n const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);\n super([err], undefined, null);\n this.message = 'MISSING_DEFINITION';\n }\n}\n"],"mappings":"+CAIA,IAAa,EAAb,cAAqD,CAAW,CAC9D,YAAY,EAAyB,CACnC,IAAM,EAAU,MAAM,6CAA6C,EAAc,KAAK,IAAI,GAAG,CAC7F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,EAAc,CACtC,KAAK,QAAU,mCAIN,EAAb,cAAqD,CAAW,CAC9D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,SAAS,EAAU,oBAAoB,CAC7D,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,kCAIN,EAAb,cAAsD,CAAW,CAC/D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,mBAAmB,EAAU,oBAAoB,CACvE,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uCAIN,EAAb,cAA2C,CAAW,CACpD,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,sBAAsB,IAAY,CACxD,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uBAIN,EAAb,cAAuC,CAAW,CAChD,YAAY,EAAY,EAA6B,EAAqC,CAOxF,IAAM,EAAsB,2BAA2B,EAAoB,KAN7C,EAAmB,QAC9C,QAAQ,KAAM,GAAG,CACjB,QAAQ,QAAS,IAAI,EAAoB,GAAG,CAIuD,eAF/E,OAAO,GAAU,SAAW,KAAK,UAAU,EAAM,CAAG,EAEyD,GAGpI,MAAM,CADU,MAAM,EAAoB,CAC/B,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,IAIN,EAAb,cAAyC,CAAW,CAClD,YAAY,EAAiB,EAA4C,CACvE,IAAM,EAAS,EAAiB,IAAI,GAAmB,IAAI,EAAkB,EAAgB,MAAO,EAAgB,oBAAqB,EAAgB,mBAAmB,CAAC,CAC7K,MAAM,EAAQ,IAAA,GAAW,KAAK,CAC9B,KAAK,QAAU,sBAAsB,EAAQ,IAAI,EAAiB,IAAI,GACpE,GAAG,EAAgB,oBAAoB,KAAK,EAAgB,mBAAmB,UAC/E,CAAC,KAAK;EAAK,KAIJ,EAAb,cAA4C,CAAW,CACrD,YAAY,EAAsB,CAChC,IAAM,EAAU,MAAM,6CAA6C,EAAW,KAAK,IAAI,GAAG,CAC1F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU"}
|
package/dist/events/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`);let n=require(`@autofleet/
|
|
1
|
+
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`);let n=require(`@autofleet/zehut`);n=e.__toESM(n);let r=require(`@autofleet/events`);r=e.__toESM(r);const i=new r.default({logger:t.default,getUserId:e=>e?.user_id??(0,n.getUser)()?.id??null}),a=[`value`,`defaultValue`,`blockEditingFromUI`],o=(e,t)=>{let n=new Set(Object.keys(e));return t.every(e=>!n.has(e))?e:{...e,...Object.fromEntries(t.map(t=>[t,typeof e[t]==`boolean`?e[t].toString():e[t]]))}},s={CustomFieldDefinition:{tableName:`dim_custom_field_definition`,eventVersion:`1`},CustomFieldValue:{tableName:`dim_custom_field_value`,eventVersion:`1`},CustomFieldEntries:{tableName:`dim_custom_field_entries`,eventVersion:`1`}},c=e=>{let n=s[e.constructor.name];if(!n)return;let r=e.get();try{r=o(e.get(),a)}catch(e){t.default.error(`Failed to convert booleans in dim event payload`,e)}i.sendObject(n.tableName,n.eventVersion,r).catch(()=>null)};exports.sendDimEvent=c;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["events: Events","Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId:
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["events: Events","Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId: payload => payload?.user_id ?? getUser()?.id ?? null,\n});\n\nconst KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];\n\nconst stringifyBooleans = (savedObject: any, keysToConvert: string[]) => {\n const savedObjectKeySet = new Set(Object.keys(savedObject));\n if (keysToConvert.every(key => !savedObjectKeySet.has(key))) {\n return savedObject;\n }\n return {\n ...savedObject,\n ...Object.fromEntries(keysToConvert.map(key => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),\n };\n};\n\nconst modelTableMapping = {\n CustomFieldDefinition: {\n tableName: 'dim_custom_field_definition',\n eventVersion: '1',\n },\n CustomFieldValue: {\n tableName: 'dim_custom_field_value',\n eventVersion: '1',\n },\n CustomFieldEntries: {\n tableName: 'dim_custom_field_entries',\n eventVersion: '1',\n },\n};\n\nexport const sendDimEvent = (instance: CustomFieldDefinition | CustomFieldValue | CustomFieldEntries | CustomValidator): void => {\n const mapping = modelTableMapping[instance.constructor.name as keyof typeof modelTableMapping];\n if (!mapping) {\n return;\n }\n let objectToSend = instance.get();\n try {\n objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);\n } catch (err) {\n logger.error('Failed to convert booleans in dim event payload', err);\n }\n\n events.sendObject(\n mapping.tableName,\n mapping.eventVersion,\n objectToSend,\n ).catch(() => null);\n};\n\nexport default events;\n"],"mappings":"8LAUA,MAAMA,EAAiB,IAAIC,EAAAA,QAAO,CAChC,OAAA,EAAA,QACA,UAAW,GAAW,GAAS,UAAA,EAAA,EAAA,UAAoB,EAAE,IAAM,KAC5D,CAAC,CAEI,EAAkB,CAAC,QAAS,eAAgB,qBAAqB,CAEjE,GAAqB,EAAkB,IAA4B,CACvE,IAAM,EAAoB,IAAI,IAAI,OAAO,KAAK,EAAY,CAAC,CAI3D,OAHI,EAAc,MAAM,GAAO,CAAC,EAAkB,IAAI,EAAI,CAAC,CAClD,EAEF,CACL,GAAG,EACH,GAAG,OAAO,YAAY,EAAc,IAAI,GAAO,CAAC,EAAK,OAAO,EAAY,IAAS,UAAY,EAAY,GAAK,UAAU,CAAG,EAAY,GAAK,CAAC,CAAC,CAC/I,EAGG,EAAoB,CACxB,sBAAuB,CACrB,UAAW,8BACX,aAAc,IACf,CACD,iBAAkB,CAChB,UAAW,yBACX,aAAc,IACf,CACD,mBAAoB,CAClB,UAAW,2BACX,aAAc,IACf,CACF,CAEY,EAAgB,GAAoG,CAC/H,IAAM,EAAU,EAAkB,EAAS,YAAY,MACvD,GAAI,CAAC,EACH,OAEF,IAAI,EAAe,EAAS,KAAK,CACjC,GAAI,CACF,EAAe,EAAkB,EAAS,KAAK,CAAE,EAAgB,OAC1D,EAAK,CACZ,EAAA,QAAO,MAAM,kDAAmD,EAAI,CAGtE,EAAO,WACL,EAAQ,UACR,EAAQ,aACR,EACD,CAAC,UAAY,KAAK"}
|
package/dist/events/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../utils/logger/index.js";import t
|
|
1
|
+
import e from"../utils/logger/index.js";import{getUser as t}from"@autofleet/zehut";import n from"@autofleet/events";const r=new n({logger:e,getUserId:e=>e?.user_id??t()?.id??null}),i=[`value`,`defaultValue`,`blockEditingFromUI`],a=(e,t)=>{let n=new Set(Object.keys(e));return t.every(e=>!n.has(e))?e:{...e,...Object.fromEntries(t.map(t=>[t,typeof e[t]==`boolean`?e[t].toString():e[t]]))}},o={CustomFieldDefinition:{tableName:`dim_custom_field_definition`,eventVersion:`1`},CustomFieldValue:{tableName:`dim_custom_field_value`,eventVersion:`1`},CustomFieldEntries:{tableName:`dim_custom_field_entries`,eventVersion:`1`}},s=t=>{let n=o[t.constructor.name];if(!n)return;let s=t.get();try{s=a(t.get(),i)}catch(t){e.error(`Failed to convert booleans in dim event payload`,t)}r.sendObject(n.tableName,n.eventVersion,s).catch(()=>null)};export{s as sendDimEvent};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/events/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["events: Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId:
|
|
1
|
+
{"version":3,"file":"index.js","names":["events: Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId: payload => payload?.user_id ?? getUser()?.id ?? null,\n});\n\nconst KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];\n\nconst stringifyBooleans = (savedObject: any, keysToConvert: string[]) => {\n const savedObjectKeySet = new Set(Object.keys(savedObject));\n if (keysToConvert.every(key => !savedObjectKeySet.has(key))) {\n return savedObject;\n }\n return {\n ...savedObject,\n ...Object.fromEntries(keysToConvert.map(key => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),\n };\n};\n\nconst modelTableMapping = {\n CustomFieldDefinition: {\n tableName: 'dim_custom_field_definition',\n eventVersion: '1',\n },\n CustomFieldValue: {\n tableName: 'dim_custom_field_value',\n eventVersion: '1',\n },\n CustomFieldEntries: {\n tableName: 'dim_custom_field_entries',\n eventVersion: '1',\n },\n};\n\nexport const sendDimEvent = (instance: CustomFieldDefinition | CustomFieldValue | CustomFieldEntries | CustomValidator): void => {\n const mapping = modelTableMapping[instance.constructor.name as keyof typeof modelTableMapping];\n if (!mapping) {\n return;\n }\n let objectToSend = instance.get();\n try {\n objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);\n } catch (err) {\n logger.error('Failed to convert booleans in dim event payload', err);\n }\n\n events.sendObject(\n mapping.tableName,\n mapping.eventVersion,\n objectToSend,\n ).catch(() => null);\n};\n\nexport default events;\n"],"mappings":"oHAUA,MAAMA,EAAiB,IAAI,EAAO,CAChC,OAAA,EACA,UAAW,GAAW,GAAS,SAAW,GAAS,EAAE,IAAM,KAC5D,CAAC,CAEI,EAAkB,CAAC,QAAS,eAAgB,qBAAqB,CAEjE,GAAqB,EAAkB,IAA4B,CACvE,IAAM,EAAoB,IAAI,IAAI,OAAO,KAAK,EAAY,CAAC,CAI3D,OAHI,EAAc,MAAM,GAAO,CAAC,EAAkB,IAAI,EAAI,CAAC,CAClD,EAEF,CACL,GAAG,EACH,GAAG,OAAO,YAAY,EAAc,IAAI,GAAO,CAAC,EAAK,OAAO,EAAY,IAAS,UAAY,EAAY,GAAK,UAAU,CAAG,EAAY,GAAK,CAAC,CAAC,CAC/I,EAGG,EAAoB,CACxB,sBAAuB,CACrB,UAAW,8BACX,aAAc,IACf,CACD,iBAAkB,CAChB,UAAW,yBACX,aAAc,IACf,CACD,mBAAoB,CAClB,UAAW,2BACX,aAAc,IACf,CACF,CAEY,EAAgB,GAAoG,CAC/H,IAAM,EAAU,EAAkB,EAAS,YAAY,MACvD,GAAI,CAAC,EACH,OAEF,IAAI,EAAe,EAAS,KAAK,CACjC,GAAI,CACF,EAAe,EAAkB,EAAS,KAAK,CAAE,EAAgB,OAC1D,EAAK,CACZ,EAAO,MAAM,kDAAmD,EAAI,CAGtE,EAAO,WACL,EAAQ,UACR,EAAQ,aACR,EACD,CAAC,UAAY,KAAK"}
|
package/dist/hooks/enrich.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../repository/definition.cjs`),t=require(`../repository/value.cjs`),n=require(`../repository/entries.cjs`),r=require(`../utils/scopeAttributes.cjs`),i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n.findEntriesByModelIds(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(
|
|
1
|
+
const e=require(`../repository/definition.cjs`),t=require(`../repository/value.cjs`),n=require(`../repository/entries.cjs`),r=require(`../utils/scopeAttributes.cjs`),i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n.findEntriesByModelIds(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(e=>e!==void 0));return e.forEach(e=>{a[e]??={}}),a},o=async({instancesIds:e,options:n,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await t.findValuesByModelIds(e,n??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),s=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{}),c=(t,n,c,l={},u={useCustomFieldsEntries:!1})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r.default(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache??=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v)),_||(_=e.findByEntityIds(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_));let y=await _;if(y.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{y.forEach(t=>{let n=t[`${e.name}.entityId`];g[n]=[]})});let b=y.reduce((e,t)=>({...e,[t.id]:t}),{});y.forEach(e=>{g[e.entityId].push(e)});let x=p.map(e=>e.id),[S,C]=await Promise.all([o({instancesIds:x,options:f,sadotOptions:u}),a({instancesIds:x,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=S[t],i=r?s(r,b):{},a=u.useCustomFieldsEntries?C[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(e=>{a[e.name]===void 0&&(a[e.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};var l=c;exports.default=l;
|
|
2
2
|
//# sourceMappingURL=enrich.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enrich.cjs","names":["applyScopeToInstance"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[],\n options?: TransactionOptions,\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(Boolean));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[],\n options?: TransactionOptions,\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (\n options.originalAttributes?.length > 0\n && !options.originalAttributes?.includes?.('customFields')\n ) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ||= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model.name}.entityId`];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map((i) => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];\n if (entityCustomFieldDefinitions?.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n options.attributesToRemove?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"sKAWM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAcY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAA,EAAA,sBACzB,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,QAAQ,CAAC,CAMnB,OAJA,EAAa,QAAS,GAAe,CACnC,EAA+B,KAAgB,EAAE,EACjD,CAEK,GAGI,EAA2B,MAAO,CAC7C,eACA,UACA,kBAMI,EAAa,uBACR,EAAE,EAGe,MAAA,EAAA,qBACxB,EACA,GAAW,EAAE,CACd,EAGwB,QAAQ,EAAK,IAAM,CAC1C,GAAM,CAAE,WAAY,EAGpB,MAFA,GAAI,KAAa,EAAE,CACnB,EAAI,GAAS,KAAK,EAAE,CACb,GACN,EAAE,CAAC,CAMF,GACJ,EACA,IAEqB,EAAkB,QAAQ,EAAK,KAAS,CAC3D,GAAG,EACH,G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,EAAK,KAAgB,CACzE,GAAG,GACF,EAAW,IAAK,EAClB,EAAG,EAAE,CAAC,CAEP,EAAuB,QAAS,GAAQ,CACtC,EAAwC,EAAI,UAAU,KAAK,EAAI,EAC/D,CAGF,IAAM,EAAe,EAAU,IAAK,GAAM,EAAE,GAAY,CAGlD,CAAC,EAAuB,GAAkC,MAAM,QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CACrC,IAAM,EAAa,EAAS,GAEtB,EAA+B,EAAwC,GACzE,GAA8B,OAAS,GACzC,EAA6B,QAAS,GAA0B,CAC1D,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACxB,EAAQ,oBAAoB,UAAW,GAAc,CACnD,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C,EAGJ,IAAA,EAAe"}
|
|
1
|
+
{"version":3,"file":"enrich.cjs","names":["applyScopeToInstance","cacheKey: string | undefined"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"sKAUM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAA,EAAA,sBACzB,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,CACnC,EAA+B,KAAgB,EAAE,EACjD,CAEK,GAGI,EAA2B,MAAO,CAC7C,eACA,UACA,kBAMI,EAAa,uBACR,EAAE,EAGe,MAAA,EAAA,qBACxB,EACA,GAAW,EAAE,CACd,EAGwB,QAA4C,EAAK,IAAM,CAC9E,GAAM,CAAE,WAAY,EAGpB,MAFA,GAAI,KAAa,EAAE,CACnB,EAAI,GAAS,KAAK,EAAE,CACb,GACN,EAAE,CAAC,CAMF,GACJ,EACA,IAEqB,EAAkB,QAAQ,EAAK,KAAS,CAC3D,GAAG,EACH,GACE,EAA2B,E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B,CACzE,GAAG,GACF,EAAW,IAAK,EAClB,EAAG,EAAE,CAAC,CAEP,EAAuB,QAAS,GAAQ,CACtC,EAAwC,EAAI,UAAU,KAAK,EAAI,EAC/D,CAGF,IAAM,EAAe,EAAU,IAAI,GAAK,EAAE,GAAY,CAGhD,CAAC,EAAuB,GAAkC,MAAM,QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C,EAGJ,IAAA,EAAe"}
|
package/dist/hooks/enrich.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{findByEntityIds as e}from"../repository/definition.js";import{findValuesByModelIds as t}from"../repository/value.js";import{findEntriesByModelIds as n}from"../repository/entries.js";import r from"../utils/scopeAttributes.js";const i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(
|
|
1
|
+
import{findByEntityIds as e}from"../repository/definition.js";import{findValuesByModelIds as t}from"../repository/value.js";import{findEntriesByModelIds as n}from"../repository/entries.js";import r from"../utils/scopeAttributes.js";const i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(e=>e!==void 0));return e.forEach(e=>{a[e]??={}}),a},o=async({instancesIds:e,options:n,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await t(e,n??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),s=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{});var c=(t,n,c,l={},u={useCustomFieldsEntries:!1})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache??=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v)),_||(_=e(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_));let y=await _;if(y.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{y.forEach(t=>{let n=t[`${e.name}.entityId`];g[n]=[]})});let b=y.reduce((e,t)=>({...e,[t.id]:t}),{});y.forEach(e=>{g[e.entityId].push(e)});let x=p.map(e=>e.id),[S,C]=await Promise.all([o({instancesIds:x,options:f,sadotOptions:u}),a({instancesIds:x,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=S[t],i=r?s(r,b):{},a=u.useCustomFieldsEntries?C[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(e=>{a[e.name]===void 0&&(a[e.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};export{c as default};
|
|
2
2
|
//# sourceMappingURL=enrich.js.map
|
package/dist/hooks/enrich.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","DefinitionRepo.findByEntityIds"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[],\n options?: TransactionOptions,\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(Boolean));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[],\n options?: TransactionOptions,\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (\n options.originalAttributes?.length > 0\n && !options.originalAttributes?.includes?.('customFields')\n ) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ||= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model.name}.entityId`];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map((i) => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];\n if (entityCustomFieldDefinitions?.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n options.attributesToRemove?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"wOAWA,MAAM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAcY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM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EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACxB,EAAQ,oBAAoB,UAAW,GAAc,CACnD,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C"}
|
|
1
|
+
{"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","cacheKey: string | undefined","DefinitionRepo.findByEntityIds"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"wOAUA,MAAM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CA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