@autofleet/sadot 1.4.20 → 1.4.21-beta-e58014c3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/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/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/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/mat-path-state.cjs +2 -0
- package/dist/mat-path-state.cjs.map +1 -0
- package/dist/mat-path-state.js +2 -0
- package/dist/mat-path-state.js.map +1 -0
- package/dist/models/index.cjs +1 -1
- package/dist/models/index.cjs.map +1 -1
- package/dist/models/index.js +1 -1
- package/dist/models/index.js.map +1 -1
- package/dist/types/index.d.cts +34 -1
- package/dist/types/index.d.ts +34 -1
- package/dist/utils/init.cjs.map +1 -1
- package/dist/utils/init.js.map +1 -1
- package/package.json +6 -6
|
@@ -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
|
|
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`),a=require(`../../../mat-path-state.cjs`);let o=require(`@autofleet/errors`),s=require(`@autofleet/node-common`);const c=(0,s.Router)({logger:t.default}),l=`CustomFieldDefinition`,u=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());c.post(`/`,async(e,a)=>{let{modelName:o}=e.params,s=u(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 ${l} request`})}}),c.get(`/:customFieldDefinitionId`,async(e,i)=>{let{customFieldDefinitionId:a}=e.params;try{let e=await n.findById(a);if(!e)throw new o.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 ${l} request`})}}),c.get(`/`,async(e,i)=>{let{params:{modelName:o},query:{entityIds:s,modelTypeId:c}}=e,d=u(o);try{let e=a.getGetEntityIdScope(),t=e?await e(s):s;if(c){let e=await n.findByModelTypeId(c,{withDisabled:!0,modelType:d,entityIds:t});return i.json(e)}let r={modelType:d,...t&&t.length>0&&{entityId:t}},o=await n.findAll(r,{withDisabled:!0,enrichWithModelTypeIds:!0});return i.json(o)}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 ${l} request`})}}),c.patch(`/:customFieldDefinitionId`,async(e,a)=>{let{customFieldDefinitionId:s,modelName:c}=e.params,d=u(c);try{let t=await i.validateCustomFieldDefinitionUpdate(e.body);if(!await n.findByWhere({id:s,modelType:d}))throw new o.ResourceNotFoundError;let r=await n.update(s,{...t,modelType:d});return a.status(200).json(r)}catch(e){return t.default.error(`Failed to patch custom field definition`,e),r.default(e,a,{logger:t.default,message:`Error in update ${l} request`})}});var d=c;exports.default=d;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","validateCustomFieldDefinitionCreation","handleError","ResourceNotFoundError","customFieldDefinitions","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[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, {\n withDisabled: true,\n modelType,\n entityIds,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","validateCustomFieldDefinitionCreation","handleError","ResourceNotFoundError","getGetEntityIdScope","customFieldDefinitions","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';\nimport { getGetEntityIdScope } from '../../../mat-path-state';\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[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // Allow consumers to expand `entityIds` (e.g. include ancestor entityIds visible via RLS)\n // before filtering. When no callback is provided, use entityIds as-is.\n const expandEntityIds = getGetEntityIdScope();\n const effectiveEntityIds = expandEntityIds ? await expandEntityIds(entityIds) : entityIds;\n\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, {\n withDisabled: true,\n modelType,\n entityIds: effectiveEntityIds,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(effectiveEntityIds && effectiveEntityIds.length > 0 && { entityId: effectiveEntityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: 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":"iUAUA,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,IAA6G,IAAK,MAAO,EAAK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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,findByModelTypeId as i,findByWhere as a,update as o}from"../../../repository/definition.js";import s from"../errors.js";import{validateCustomFieldDefinitionCreation as c,validateCustomFieldDefinitionUpdate as l}from"./validations.js";import{
|
|
1
|
+
import e from"../../../utils/logger/index.js";import{create as t,findAll as n,findById as r,findByModelTypeId as i,findByWhere as a,update as o}from"../../../repository/definition.js";import s from"../errors.js";import{validateCustomFieldDefinitionCreation as c,validateCustomFieldDefinitionUpdate as l}from"./validations.js";import{getGetEntityIdScope as u}from"../../../mat-path-state.js";import{ResourceNotFoundError as d}from"@autofleet/errors";import{Router as f}from"@autofleet/node-common";const p=f({logger:e}),m=`CustomFieldDefinition`,h=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());p.post(`/`,async(n,r)=>{let{modelName:i}=n.params,a=h(i);try{let e=await t({...await c(n.body),modelType:a});return r.status(201).json(e)}catch(t){return e.error(`Failed to create custom field definition`,t),s(t,r,{logger:e,message:`Error in create ${m} request`})}}),p.get(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:i}=t.params;try{let e=await r(i);if(!e)throw new d;return n.json(e)}catch(t){return e.error(`Failed to fetch custom field definition`,t),s(t,n,{logger:e,message:`Error in get ${m} request`})}}),p.get(`/`,async(t,r)=>{let{params:{modelName:a},query:{entityIds:o,modelTypeId:c}}=t,l=h(a);try{let e=u(),t=e?await e(o):o;if(c){let e=await i(c,{withDisabled:!0,modelType:l,entityIds:t});return r.json(e)}let a=await n({modelType:l,...t&&t.length>0&&{entityId:t}},{withDisabled:!0,enrichWithModelTypeIds:!0});return r.json(a)}catch(t){return e.error(`Failed to fetch custom field definitions`,t),s(t,r,{logger:e,message:`Error in get all ${m} request`})}}),p.patch(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:r,modelName:i}=t.params,c=h(i);try{let e=await l(t.body);if(!await a({id:r,modelType:c}))throw new d;let i=await o(r,{...e,modelType:c});return n.status(200).json(i)}catch(t){return e.error(`Failed to patch custom field definition`,t),s(t,n,{logger:e,message:`Error in update ${m} request`})}});var g=p;export{g 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","customFieldDefinitions","DefinitionRepo.findByModelTypeId","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[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, {\n withDisabled: true,\n modelType,\n entityIds,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(
|
|
1
|
+
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","DefinitionRepo.create","handleError","DefinitionRepo.findById","customFieldDefinitions","DefinitionRepo.findByModelTypeId","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';\nimport { getGetEntityIdScope } from '../../../mat-path-state';\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[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // Allow consumers to expand `entityIds` (e.g. include ancestor entityIds visible via RLS)\n // before filtering. When no callback is provided, use entityIds as-is.\n const expandEntityIds = getGetEntityIdScope();\n const effectiveEntityIds = expandEntityIds ? await expandEntityIds(entityIds) : entityIds;\n\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, {\n withDisabled: true,\n modelType,\n entityIds: effectiveEntityIds,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(effectiveEntityIds && effectiveEntityIds.length > 0 && { entityId: effectiveEntityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: 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":"ifAUA,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,Q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,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,CACrDP,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
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(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,hasTypeId:!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));let y;if(!_)
|
|
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,hasTypeId:!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));let y;if(!_){let n=u.hasTypeId&&p.length>0&&p[0].typeId,r=async(r=f.transaction)=>{if(n){let n=[...new Set(p.map(e=>e.typeId).filter(Boolean))];y=new Map,n.forEach(e=>y.set(e,new Set));let i=(await Promise.all(n.map(async n=>{let i=await e.findByModelTypeId(n,{withDisabled:!1,entityIds:h,modelType:t,modelOptions:l,transaction:r});return i.forEach(e=>y.get(n).add(e.id)),i}))).flat(),a=new Map;return i.forEach(e=>{a.set(e.id,e)}),Array.from(a.values())}return e.findByEntityIds(t,h,{transaction:r,modelOptions:l,attributes:i})};_=u.matPathManager&&u.isMatPathActive?.()?u.matPathManager.withPaths(e=>r(e),{transaction:f.transaction}):r(),n||f.transaction?.definitionCache?.set(v,_)}let b=await _;if(b.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{b.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!g[n]&&(g[n]=[])})});let x=b.reduce((e,t)=>({...e,[t.id]:t}),{});b.forEach(e=>{let t=e.entityId;if(l?.useEntityIdFromInclude&&l.include){let n=l.include(m);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}g[t]&&g[t].push(e)});let S=p.map(e=>e.id),[C,w]=await Promise.all([o({instancesIds:S,options:f,sadotOptions:u}),a({instancesIds:S,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=C[t],i=r?s(r,x):{},a=u.useCustomFieldsEntries?w[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(t=>{y&&!y.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.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","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<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' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: 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 let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction)\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction: options.transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n customFieldDefinitionsPromise = Promise.resolve(Array.from(uniqueDefinitionsMap.values()));\n } else {\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 }\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: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\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 (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\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,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AGF,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,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,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"}
|
|
1
|
+
{"version":3,"file":"enrich.cjs","names":["applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<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' | 'hasTypeId' | 'matPathManager' | 'isMatPathActive'> = { useCustomFieldsEntries: false, hasTypeId: 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 let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction).\n // When mat-path is active, run inside withPaths(ANCESTORS) so RLS on joined tables\n // (e.g. Context) filters CFDs to those visible at the caller's path + its ancestors.\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n const fetchDefinitions = async (transaction = options.transaction) => {\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n return Array.from(uniqueDefinitionsMap.values());\n }\n return DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n };\n\n customFieldDefinitionsPromise = sadotOptions.matPathManager && sadotOptions.isMatPathActive?.()\n ? sadotOptions.matPathManager.withPaths(\n transaction => fetchDefinitions(transaction),\n { transaction: options.transaction },\n )\n : fetchDefinitions();\n\n if (!shouldApplyTypeFiltering) {\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\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: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\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 (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\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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AAa,QAAS,CAChE,IAAM,EAAkB,EAAa,QAAQ,EAAY,CACzD,IAAK,GAAM,CAAE,WAAW,EAAiB,CACvC,IAAM,EAAiB,EAAI,EAAO,OAAO,UAAY,EAAI,GAAG,EAAO,KAAK,YACxE,GAAI,EAAgB,CAClB,EAAgB,EAChB,QAKF,EAAwC,IAC1C,EAAwC,GAAe,KAAK,EAAI,EAElE,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,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,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,findByModelTypeId as t}from"../repository/definition.js";import{findValuesByModelIds as n}from"../repository/value.js";import{findEntriesByModelIds as r}from"../repository/entries.js";import i from"../utils/scopeAttributes.js";const a=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],o=async({instancesIds:e,options:t,sadotOptions:n})=>{if(!n.useCustomFieldsEntries)return{};let i=await r(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},s=async({instancesIds:e,options:t,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await n(e,t??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),c=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{});var l=(n,r,l,u={},d={useCustomFieldsEntries:!1,hasTypeId:!1})=>async(f,p)=>{if(p.originalAttributes?.length>0&&!p.originalAttributes?.includes?.(`customFields`))return;let m=Array.isArray(f)?f:[f];m=m.filter(Boolean);let h=i(m,r),g=[...new Set(h)].filter(Boolean),_=g.reduce((e,t)=>({...e,[t]:[]}),{}),v,y;p.transaction&&(p.transaction.definitionCache??=new Map,y=`${n}:${g.slice().sort().join(`,`)}`,v=p.transaction.definitionCache.get(y));let b;if(!v)
|
|
1
|
+
import{findByEntityIds as e,findByModelTypeId as t}from"../repository/definition.js";import{findValuesByModelIds as n}from"../repository/value.js";import{findEntriesByModelIds as r}from"../repository/entries.js";import i from"../utils/scopeAttributes.js";const a=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],o=async({instancesIds:e,options:t,sadotOptions:n})=>{if(!n.useCustomFieldsEntries)return{};let i=await r(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},s=async({instancesIds:e,options:t,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await n(e,t??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),c=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{});var l=(n,r,l,u={},d={useCustomFieldsEntries:!1,hasTypeId:!1})=>async(f,p)=>{if(p.originalAttributes?.length>0&&!p.originalAttributes?.includes?.(`customFields`))return;let m=Array.isArray(f)?f:[f];m=m.filter(Boolean);let h=i(m,r),g=[...new Set(h)].filter(Boolean),_=g.reduce((e,t)=>({...e,[t]:[]}),{}),v,y;p.transaction&&(p.transaction.definitionCache??=new Map,y=`${n}:${g.slice().sort().join(`,`)}`,v=p.transaction.definitionCache.get(y));let b;if(!v){let r=d.hasTypeId&&m.length>0&&m[0].typeId,i=async(i=p.transaction)=>{if(r){let e=[...new Set(m.map(e=>e.typeId).filter(Boolean))];b=new Map,e.forEach(e=>b.set(e,new Set));let r=(await Promise.all(e.map(async e=>{let r=await t(e,{withDisabled:!1,entityIds:g,modelType:n,modelOptions:u,transaction:i});return r.forEach(t=>b.get(e).add(t.id)),r}))).flat(),a=new Map;return r.forEach(e=>{a.set(e.id,e)}),Array.from(a.values())}return e(n,g,{transaction:i,modelOptions:u,attributes:a})};v=d.matPathManager&&d.isMatPathActive?.()?d.matPathManager.withPaths(e=>i(e),{transaction:p.transaction}):i(),r||p.transaction?.definitionCache?.set(y,v)}let x=await v;if(x.length===0){m.forEach(e=>{e.customFields={}});return}u?.include&&u.useEntityIdFromInclude&&u.include(h).forEach(({model:e})=>{x.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!_[n]&&(_[n]=[])})});let S=x.reduce((e,t)=>({...e,[t.id]:t}),{});x.forEach(e=>{let t=e.entityId;if(u?.useEntityIdFromInclude&&u.include){let n=u.include(h);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}_[t]&&_[t].push(e)});let C=m.map(e=>e.id),[w,T]=await Promise.all([s({instancesIds:C,options:p,sadotOptions:d}),o({instancesIds:C,options:p,sadotOptions:d})]);m.forEach(e=>{let{id:t}=e,n=w[t],i=n?c(n,S):{},a=d.useCustomFieldsEntries?T[t]:i;r.forEach(t=>{let n=_[e[t]];n&&n.length>0&&n.forEach(t=>{b&&!b.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.name]=null)})}),e.customFields=a,p.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),l===`afterFind`&&e?.changed?.(`customFields`,!1)})};export{l 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","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined","DefinitionRepo.findByModelTypeId","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' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: 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 let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction)\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction: options.transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n customFieldDefinitionsPromise = Promise.resolve(Array.from(uniqueDefinitionsMap.values()));\n } else {\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 }\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: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\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 (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\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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S,GAA0B,CAC1D,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,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"}
|
|
1
|
+
{"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined","DefinitionRepo.findByModelTypeId","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' | 'hasTypeId' | 'matPathManager' | 'isMatPathActive'> = { useCustomFieldsEntries: false, hasTypeId: 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 let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction).\n // When mat-path is active, run inside withPaths(ANCESTORS) so RLS on joined tables\n // (e.g. Context) filters CFDs to those visible at the caller's path + its ancestors.\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n const fetchDefinitions = async (transaction = options.transaction) => {\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n return Array.from(uniqueDefinitionsMap.values());\n }\n return DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n };\n\n customFieldDefinitionsPromise = sadotOptions.matPathManager && sadotOptions.isMatPathActive?.()\n ? sadotOptions.matPathManager.withPaths(\n transaction => fetchDefinitions(transaction),\n { transaction: options.transaction },\n )\n : fetchDefinitions();\n\n if (!shouldApplyTypeFiltering) {\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\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: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\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 (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\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":"+PAUA,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,CAGX,IAAM,EAAqB,MAAMA,EAC/B,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,MAAMC,EAC9B,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,EAAI,0BAC5B,EAAG,EAA2B,EAAI,yBAAyB,MAAO,EAAI,MAAO,CAEnF,EAAG,EAAE,CAAC,CA4MT,IAAA,GArME,EACA,EACA,EACA,EAA6B,EAAE,CAC/B,EAAwH,CAAE,uBAAwB,GAAO,UAAW,GAAO,GACxK,MACH,EACA,IACkB,CAClB,GAAI,EAAQ,oBAAoB,OAAS,GAAK,CAAC,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A,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,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,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"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./utils/logger/index.cjs`),t=require(`./utils/constants/index.cjs`),n=require(`./models/CustomFieldValue.cjs`),r=require(`./models/CustomFieldDefinition.cjs`),i=require(`./models/CustomFieldEntries.cjs`),a=require(`./models/CustomValidator.cjs`),o=require(`./models/index.cjs`),s=require(`./api/index.cjs`),
|
|
1
|
+
Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./utils/logger/index.cjs`),t=require(`./utils/constants/index.cjs`),n=require(`./models/CustomFieldValue.cjs`),r=require(`./models/CustomFieldDefinition.cjs`),i=require(`./models/CustomFieldEntries.cjs`),a=require(`./models/CustomValidator.cjs`),o=require(`./models/index.cjs`),s=require(`./mat-path-state.cjs`),c=require(`./api/index.cjs`),l=require(`./utils/db/index.cjs`),u=require(`./utils/helpers/index.cjs`),d=require(`./scopes/filter.cjs`),f=require(`./utils/init.cjs`),p=require(`./init-state.cjs`),m=require(`./utils/validations/schema/custom-fields.cjs`),h=new p.SadotInitializationState,g=async(t,n,r)=>{e.tryAddingTraceIdMiddleware();let{models:i,useCustomFieldsEntries:a,useModelTypeMapping:u,matPathManager:d,isMatPathActive:p}=r;s.setGetEntityIdScope(r.getEntityIdScope),t&&t.use(`/api`,c.default);let m=r.sequelize??l.default(r.databaseConfig);return process.env.NODE_ENV===`test`&&await o.initTestModels(m),f.addHooks(i,n,{useCustomFieldsEntries:a,matPathManager:d,isMatPathActive:p}),await o.initTables(m,r.getUser,{useCustomFieldsEntries:a,useModelTypeMapping:u,isMatPathActive:p}),f.addScopes(i,n,{useCustomFieldsEntries:a}),f.applyCustomAssociation(i),e.default.debug(`sadot - custom fields finished initializing with models`,i),m},_=async(e,t,n)=>{let r=g(e,t,n);return h.setInitPromise(r,!n.sequelize),await r};var v=_;const y=(e,t)=>{f.removeHooks(e,t)};exports.CUSTOM_FIELDS_FILTER_SCOPE=t.CUSTOM_FIELDS_FILTER_SCOPE,exports.CustomFieldDefinition=r.default,exports.CustomFieldDefinitionType=t.CustomFieldDefinitionType,exports.CustomFieldEntries=i.default,exports.CustomFieldValue=n.default,exports.CustomFieldsSchema=m.CustomFieldsSchema,exports.CustomValidator=a.default,exports.customFieldsSortScope=d.customFieldsSortScope,exports.default=v,exports.disableCustomFields=y,exports.generateCustomFieldSearchQueryPayload=u.generateCustomFieldSearchQueryPayload,exports.generateRandomString=u.generateRandomString,exports.sadotInitState=h,exports.supportedEntities=t.supportedEntities;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["sadotInitState: SadotInitializationState","SadotInitializationState","api","initDB","initTestModels","initTables"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\nimport { SadotInitializationState } from './init-state';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping } = options;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["sadotInitState: SadotInitializationState","SadotInitializationState","api","initDB","initTestModels","initTables"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\nimport { SadotInitializationState } from './init-state';\nimport { setGetEntityIdScope } from './mat-path-state';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping, matPathManager, isMatPathActive } = options;\n setGetEntityIdScope(options.getEntityIdScope);\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries, matPathManager, isMatPathActive });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping, isMatPathActive });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"6nBA6BaA,EAA2C,IAAIC,EAAAA,yBAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,EAAA,4BAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,sBAAqB,iBAAgB,mBAAoB,EACjG,EAAA,oBAAoB,EAAQ,iBAAiB,CACzC,GACF,EAAI,IAAI,OAAQC,EAAAA,QAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAAA,QAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAMC,EAAAA,eAAe,EAAU,CAGjC,EAAA,SAAS,EAAQ,EAAU,CAAE,yBAAwB,iBAAgB,kBAAiB,CAAC,CACvF,MAAMC,EAAAA,WAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,sBAAqB,kBAAiB,CAAC,CAC9G,EAAA,UAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAA,uBAAuB,EAAO,CAE9B,EAAA,QAAO,MAAM,0DAA2D,EAAO,CACxE,GAOH,EAAkB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAGf,IAAA,EAAe,EAEf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAA,YAAY,EAAQ,EAAS"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e,{tryAddingTraceIdMiddleware as t}from"./utils/logger/index.js";import{CUSTOM_FIELDS_FILTER_SCOPE as n,CustomFieldDefinitionType as r,supportedEntities as i}from"./utils/constants/index.js";import a from"./models/CustomFieldValue.js";import o from"./models/CustomFieldDefinition.js";import s from"./models/CustomFieldEntries.js";import c from"./models/CustomValidator.js";import{initTables as l,initTestModels as u}from"./models/index.js";import d from"./api/index.js";import
|
|
1
|
+
import e,{tryAddingTraceIdMiddleware as t}from"./utils/logger/index.js";import{CUSTOM_FIELDS_FILTER_SCOPE as n,CustomFieldDefinitionType as r,supportedEntities as i}from"./utils/constants/index.js";import a from"./models/CustomFieldValue.js";import o from"./models/CustomFieldDefinition.js";import s from"./models/CustomFieldEntries.js";import c from"./models/CustomValidator.js";import{initTables as l,initTestModels as u}from"./models/index.js";import{setGetEntityIdScope as d}from"./mat-path-state.js";import f from"./api/index.js";import p from"./utils/db/index.js";import{generateCustomFieldSearchQueryPayload as m,generateRandomString as h}from"./utils/helpers/index.js";import{customFieldsSortScope as g}from"./scopes/filter.js";import{addHooks as _,addScopes as v,applyCustomAssociation as y,removeHooks as b}from"./utils/init.js";import{SadotInitializationState as x}from"./init-state.js";import{CustomFieldsSchema as S}from"./utils/validations/schema/custom-fields.js";const C=new x,w=async(n,r,i)=>{t();let{models:a,useCustomFieldsEntries:o,useModelTypeMapping:s,matPathManager:c,isMatPathActive:m}=i;d(i.getEntityIdScope),n&&n.use(`/api`,f);let h=i.sequelize??p(i.databaseConfig);return process.env.NODE_ENV===`test`&&await u(h),_(a,r,{useCustomFieldsEntries:o,matPathManager:c,isMatPathActive:m}),await l(h,i.getUser,{useCustomFieldsEntries:o,useModelTypeMapping:s,isMatPathActive:m}),v(a,r,{useCustomFieldsEntries:o}),y(a),e.debug(`sadot - custom fields finished initializing with models`,a),h};var T=async(e,t,n)=>{let r=w(e,t,n);return C.setInitPromise(r,!n.sequelize),await r};const E=(e,t)=>{b(e,t)};export{n as CUSTOM_FIELDS_FILTER_SCOPE,o as CustomFieldDefinition,r as CustomFieldDefinitionType,s as CustomFieldEntries,a as CustomFieldValue,S as CustomFieldsSchema,c as CustomValidator,g as customFieldsSortScope,T as default,E as disableCustomFields,m as generateCustomFieldSearchQueryPayload,h as generateRandomString,C as sadotInitState,i as supportedEntities};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["sadotInitState: SadotInitializationState","api","initDB"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\nimport { SadotInitializationState } from './init-state';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping } = options;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["sadotInitState: SadotInitializationState","api","initDB"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\nimport { SadotInitializationState } from './init-state';\nimport { setGetEntityIdScope } from './mat-path-state';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping, matPathManager, isMatPathActive } = options;\n setGetEntityIdScope(options.getEntityIdScope);\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries, matPathManager, isMatPathActive });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping, isMatPathActive });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"m9BA6BA,MAAaA,EAA2C,IAAI,EAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,GAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,sBAAqB,iBAAgB,mBAAoB,EACjG,EAAoB,EAAQ,iBAAiB,CACzC,GACF,EAAI,IAAI,OAAQC,EAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAM,EAAe,EAAU,CAGjC,EAAS,EAAQ,EAAU,CAAE,yBAAwB,iBAAgB,kBAAiB,CAAC,CACvF,MAAM,EAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,sBAAqB,kBAAiB,CAAC,CAC9G,EAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAuB,EAAO,CAE9B,EAAO,MAAM,0DAA2D,EAAO,CACxE,GAmBT,IAAA,EAZwB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAKf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAY,EAAQ,EAAS"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mat-path-state.cjs","names":["getEntityIdScope: CustomFieldOptions['getEntityIdScope']"],"sources":["../src/mat-path-state.ts"],"sourcesContent":["import type { CustomFieldOptions } from './types';\n\n/**\n * Module-scoped holder for the optional `getEntityIdScope` callback so route handlers\n * can read it without threading it through every signature. Set once during init.\n */\nlet getEntityIdScope: CustomFieldOptions['getEntityIdScope'];\n\nexport const setGetEntityIdScope = (fn: CustomFieldOptions['getEntityIdScope']): void => {\n getEntityIdScope = fn;\n};\n\nexport const getGetEntityIdScope = (): CustomFieldOptions['getEntityIdScope'] => getEntityIdScope;\n"],"mappings":"AAMA,IAAIA,EAEJ,MAAa,EAAuB,GAAqD,CACvF,EAAmB,GAGR,MAAoE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mat-path-state.js","names":["getEntityIdScope: CustomFieldOptions['getEntityIdScope']"],"sources":["../src/mat-path-state.ts"],"sourcesContent":["import type { CustomFieldOptions } from './types';\n\n/**\n * Module-scoped holder for the optional `getEntityIdScope` callback so route handlers\n * can read it without threading it through every signature. Set once during init.\n */\nlet getEntityIdScope: CustomFieldOptions['getEntityIdScope'];\n\nexport const setGetEntityIdScope = (fn: CustomFieldOptions['getEntityIdScope']): void => {\n getEntityIdScope = fn;\n};\n\nexport const getGetEntityIdScope = (): CustomFieldOptions['getEntityIdScope'] => getEntityIdScope;\n"],"mappings":"AAMA,IAAIA,EAEJ,MAAa,EAAuB,GAAqD,CACvF,EAAmB,GAGR,MAAoE"}
|
package/dist/models/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`);let d=require(`sequelize`);const f=[a.default,i.default,s.default,o.default],p=`sadot-migration`,m=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,h=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1}={})=>{let
|
|
1
|
+
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`);let d=require(`sequelize`);const f=[a.default,i.default,s.default,o.default],p=`sadot-migration`,m=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,h=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1,isMatPathActive:p}={})=>{let m=`${a}_${o}${s?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let h=[r.default,n.default,l.default,...s?[c.default]:[],...f?[u.default]:[]];e.addModels(h),f&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{if(p?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),l.default.addScope(`userScope`,()=>{if(p?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`);let g=e.define(`SequelizeMeta`,{name:{type:d.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let _=await g.findAll({where:{name:{[d.Op.like]:`${a}%`}},raw:!0}),v=_.at(-1),y=_.findIndex(e=>e.name===m);if(t.default.info(`custom-fields: migrations`,{currentMigrations:_,currentSadotSchemaVersion:v,newSadotSchemaVersion:m,expectedSchemaVersionIndex:y}),!v||v.name!==m){t.default.info(`custom-fields: syncing models`);try{if(await r.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldDefinition synced successfully`),await n.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldValue synced successfully`),await l.default.sync({alter:!0}),t.default.info(`custom-fields: CustomValidator synced successfully`),s&&(await c.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldEntries synced successfully`)),f&&(await u.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),y===-1&&(await g.create({name:m}),t.default.info(`custom-fields: SequelizeMeta entry created successfully`)),t.default.info(`custom-fields: models synced`),_.length&&y!==-1&&y<_.length-1){let e=_.slice(y+1);t.default.info(`custom-fields: deleting newer migrations during down migration`,{count:e.length}),await g.destroy({where:{name:{[d.Op.in]:e.map(e=>e.name)}}}),t.default.info(`custom-fields: newer migrations deleted successfully`)}}catch(e){throw t.default.error(`custom-fields: failed to sync models`,{error:e}),e}}},g=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(f),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=h,exports.initTestModels=g;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","DataTypes","Op"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"sgBAsBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAEjB,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,IACD,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAA,QAAO,KAAK,iDAAiD,CAEzD,CAACC,E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AE,CAAE,CAAC,CAC3G,EAAA,QAAO,KAAK,uDAAuD,QAE9D,EAAO,CAEd,MADA,EAAA,QAAO,MAAM,uCAAwC,CAAE,QAAO,CAAC,CACzD,KAKN,EAAiB,KAAO,IAAwC,CAGpE,GAFA,EAAA,QAAO,KAAK,sDAAsD,CAE9D,CAACR,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAMA,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAMA,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAA,QAAO,KAAK,mCAAmC,CAC/C,MAAMJ,EAAAA,QAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAAA,QAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAAA,QAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAAA,QAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAA,QAAO,KAAK,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","DataTypes","Op"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n isMatPathActive?: CustomFieldOptions['isMatPathActive'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n isMatPathActive,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathActive?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathActive?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"sgBAuBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAEjB,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,GACtB,mBACqB,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAA,QAAO,KAAK,iDAAiD,CAEzD,CAACC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EAAAA,QACAC,EAAAA,QACAC,EAAAA,QACA,GAAI,EAAyB,CAACC,EAAAA,QAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAAA,QAAwB,CAAG,EAAE,CACzD,CAED,EAAU,UAAU,EAAiB,CAGjC,IACF,EAAA,QAAsB,QAAQA,EAAAA,QAAyB,CACrD,WAAY,0BACZ,GAAI,oBACL,CAAC,CACF,EAAA,QAAwB,UAAUJ,EAAAA,QAAuB,CACvD,WAAY,0BACZ,GAAI,wBACL,CAAC,EAGJ,EAAA,QAAsB,SAAS,gBAAmB,CAKhD,GAAI,KAAmB,CAAE,MAAO,EAAE,CAClC,IAAM,EAAO,GAAS,CAItB,OAHK,GAAM,YAGJ,CACL,MAAO,CACL,SAAU,CACR,GAAG,OAAO,KAAK,EAAK,YAAY,OAAO,CACvC,GAAG,OAAO,KAAK,EAAK,YAAY,eAAe,CAC/C,GAAG,OAAO,KAAK,EAAK,YAAY,cAAc,CAC/C,CACF,CACF,CAVQ,EAAE,EAWX,CAEF,EAAA,QAAgB,SAAS,gBAAmB,CAC1C,GAAI,KAAmB,CAAE,MAAO,EAAE,CAClC,I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GED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{DataTypes as u,Op as d}from"sequelize";const f=[i,r,o,a],p=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:f=!1,useModelTypeMapping:p=!1}={})=>{let
|
|
1
|
+
import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{DataTypes as u,Op as d}from"sequelize";const f=[i,r,o,a],p=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:f=!1,useModelTypeMapping:p=!1,isMatPathActive:m}={})=>{let h=`${a}_${o}${f?`_withEntries`:``}${p?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let g=[n,t,c,...f?[s]:[],...p?[l]:[]];r.addModels(g),p&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),c.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),e.info(`custom-fields: models added`);let _=r.define(`SequelizeMeta`,{name:{type:u.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let v=await _.findAll({where:{name:{[d.like]:`${a}%`}},raw:!0}),y=v.at(-1),b=v.findIndex(e=>e.name===h);if(e.info(`custom-fields: migrations`,{currentMigrations:v,currentSadotSchemaVersion:y,newSadotSchemaVersion:h,expectedSchemaVersionIndex:b}),!y||y.name!==h){e.info(`custom-fields: syncing models`);try{if(await n.sync({alter:!0}),e.info(`custom-fields: CustomFieldDefinition synced successfully`),await t.sync({alter:!0}),e.info(`custom-fields: CustomFieldValue synced successfully`),await c.sync({alter:!0}),e.info(`custom-fields: CustomValidator synced successfully`),f&&(await s.sync({alter:!0}),e.info(`custom-fields: CustomFieldEntries synced successfully`)),p&&(await l.sync({alter:!0}),e.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),b===-1&&(await _.create({name:h}),e.info(`custom-fields: SequelizeMeta entry created successfully`)),e.info(`custom-fields: models synced`),v.length&&b!==-1&&b<v.length-1){let t=v.slice(b+1);e.info(`custom-fields: deleting newer migrations during down migration`,{count:t.length}),await _.destroy({where:{name:{[d.in]:t.map(e=>e.name)}}}),e.info(`custom-fields: newer migrations deleted successfully`)}}catch(t){throw e.error(`custom-fields: failed to sync models`,{error:t}),t}}},m=async t=>{if(e.info(`custom-fields: initialize custom-fields test models`),!t.addModels)throw Error(`sequelize instance must have addModels function`);t.addModels(f),await t.dropSchema(`custom-fields`,{logging:!1}),await t.createSchema(`custom-fields`,{logging:!1}),e.info(`custom-fields: test models added`),await i.sync({alter:!0}),await r.sync({alter:!0}),await a.sync({alter:!0}),await o.sync({alter:!0}),e.info(`custom-fields: test models synced`)};export{p as initTables,m as initTestModels};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/models/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"+eAsBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAKtF,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,IACD,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAO,KAAK,iDAAiD,CAEzD,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EACAC,EACAC,EACA,GAAI,EAAyB,CAACC,EAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAwB,CAAG,EAAE,CACzD,CAED,EAAU,UAAU,EAAiB,CAGjC,IACF,EAAsB,QAAQA,EAAyB,CACrD,WAAY,0BACZ,GAAI,oBACL,CAAC,CACF,EAAwB,UAAUJ,EAAuB,CACvD,WAAY,0BACZ,GAAI,wBACL,CAAC,EAGJ,EAAsB,SAAS,gBAAmB,CAChD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,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n isMatPathActive?: CustomFieldOptions['isMatPathActive'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n isMatPathActive,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathActive?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathActive?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"+eAuBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAKtF,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,GACtB,mBACqB,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAO,KAAK,iDAAiD,CAEzD,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EACAC,EACAC,EACA,GAAI,EAAyB,CAACC,EAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAwB,CAAG,EAAE,CACzD,CAED,EAAU,UAAU,EAAiB,CAGjC,IACF,EAAsB,QAAQA,EAAyB,CACrD,WAAY,0BACZ,GAAI,oBACL,CAAC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AAMT,EAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
|
package/dist/types/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CustomFieldDefinition } from "../models/CustomFieldDefinition.cjs";
|
|
2
2
|
import { ModelCtor, Sequelize } from "sequelize-typescript";
|
|
3
|
-
import { IncludeOptions } from "sequelize";
|
|
3
|
+
import { IncludeOptions, Transaction } from "sequelize";
|
|
4
4
|
import { getUser } from "@autofleet/zehut";
|
|
5
5
|
|
|
6
6
|
//#region src/types/index.d.ts
|
|
@@ -42,6 +42,18 @@ interface Models {
|
|
|
42
42
|
updateWebhookHandler?: (instance: any) => any;
|
|
43
43
|
deletionWebhookHandler?: (instance: any) => any;
|
|
44
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* Minimal structural type for an `@autofleet/mat-path` MatPathManager.
|
|
47
|
+
* Defined here to avoid taking a runtime dependency on mat-path.
|
|
48
|
+
*
|
|
49
|
+
* The scoping mode (ancestors/descendants/etc.) is configured by the consumer at
|
|
50
|
+
* app level via `matPathManager.setScopingMode({ <table>: <mode> })`, not per call.
|
|
51
|
+
*/
|
|
52
|
+
interface MatPathLike {
|
|
53
|
+
withPaths<T>(callback: (transaction?: Transaction) => Promise<T>, options?: {
|
|
54
|
+
transaction?: Transaction;
|
|
55
|
+
}): Promise<T>;
|
|
56
|
+
}
|
|
45
57
|
interface CustomFieldOptions {
|
|
46
58
|
models: Models[];
|
|
47
59
|
hasTypeId?: boolean;
|
|
@@ -52,6 +64,27 @@ interface CustomFieldOptions {
|
|
|
52
64
|
useValidators?: boolean;
|
|
53
65
|
useModelTypeMapping?: boolean;
|
|
54
66
|
getRequiredCustomFields?: (instance: any, fieldDefinitions: CustomFieldDefinition[], options: any) => Promise<string[]> | string[];
|
|
67
|
+
/**
|
|
68
|
+
* Optional mat-path manager used to wrap CustomFieldDefinition queries in `withPaths(ANCESTORS)`,
|
|
69
|
+
* so RLS on joined tables (e.g. Context) filters CFDs to those visible at the caller's path
|
|
70
|
+
* + its ancestors.
|
|
71
|
+
*/
|
|
72
|
+
matPathManager?: MatPathLike;
|
|
73
|
+
/**
|
|
74
|
+
* Optional predicate that returns true when mat-path RLS is currently active for this request
|
|
75
|
+
* (typically: enabled AND the request carries context paths). When it returns true, sadot's
|
|
76
|
+
* `userScope` becomes a no-op so RLS is the sole filter.
|
|
77
|
+
*/
|
|
78
|
+
isMatPathActive?: () => boolean;
|
|
79
|
+
/**
|
|
80
|
+
* Optional callback used by the `GET /custom-field-definitions/:modelName` handler to expand
|
|
81
|
+
* the `entityIds` query parameter — typically to include ancestor entityIds the caller can
|
|
82
|
+
* see (e.g. partner-level contexts above the requested fleet). Receives the raw `entityIds`
|
|
83
|
+
* from the request (or `undefined` when not provided) and returns the list to filter by.
|
|
84
|
+
*
|
|
85
|
+
* Only invoked when provided; when omitted, the handler uses `entityIds` as-is.
|
|
86
|
+
*/
|
|
87
|
+
getEntityIdScope?: (entityIds: string[] | undefined) => Promise<string[] | undefined> | string[] | undefined;
|
|
55
88
|
}
|
|
56
89
|
//#endregion
|
|
57
90
|
export { CustomFieldOptions, ModelFetcher, Models };
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CustomFieldDefinition } from "../models/CustomFieldDefinition.js";
|
|
2
2
|
import "../models/CustomValidator.js";
|
|
3
|
-
import { IncludeOptions } from "sequelize";
|
|
3
|
+
import { IncludeOptions, Transaction } from "sequelize";
|
|
4
4
|
import { getUser } from "@autofleet/zehut";
|
|
5
5
|
import { ModelCtor, Sequelize } from "sequelize-typescript";
|
|
6
6
|
|
|
@@ -43,6 +43,18 @@ interface Models {
|
|
|
43
43
|
updateWebhookHandler?: (instance: any) => any;
|
|
44
44
|
deletionWebhookHandler?: (instance: any) => any;
|
|
45
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* Minimal structural type for an `@autofleet/mat-path` MatPathManager.
|
|
48
|
+
* Defined here to avoid taking a runtime dependency on mat-path.
|
|
49
|
+
*
|
|
50
|
+
* The scoping mode (ancestors/descendants/etc.) is configured by the consumer at
|
|
51
|
+
* app level via `matPathManager.setScopingMode({ <table>: <mode> })`, not per call.
|
|
52
|
+
*/
|
|
53
|
+
interface MatPathLike {
|
|
54
|
+
withPaths<T>(callback: (transaction?: Transaction) => Promise<T>, options?: {
|
|
55
|
+
transaction?: Transaction;
|
|
56
|
+
}): Promise<T>;
|
|
57
|
+
}
|
|
46
58
|
interface CustomFieldOptions {
|
|
47
59
|
models: Models[];
|
|
48
60
|
hasTypeId?: boolean;
|
|
@@ -53,6 +65,27 @@ interface CustomFieldOptions {
|
|
|
53
65
|
useValidators?: boolean;
|
|
54
66
|
useModelTypeMapping?: boolean;
|
|
55
67
|
getRequiredCustomFields?: (instance: any, fieldDefinitions: CustomFieldDefinition[], options: any) => Promise<string[]> | string[];
|
|
68
|
+
/**
|
|
69
|
+
* Optional mat-path manager used to wrap CustomFieldDefinition queries in `withPaths(ANCESTORS)`,
|
|
70
|
+
* so RLS on joined tables (e.g. Context) filters CFDs to those visible at the caller's path
|
|
71
|
+
* + its ancestors.
|
|
72
|
+
*/
|
|
73
|
+
matPathManager?: MatPathLike;
|
|
74
|
+
/**
|
|
75
|
+
* Optional predicate that returns true when mat-path RLS is currently active for this request
|
|
76
|
+
* (typically: enabled AND the request carries context paths). When it returns true, sadot's
|
|
77
|
+
* `userScope` becomes a no-op so RLS is the sole filter.
|
|
78
|
+
*/
|
|
79
|
+
isMatPathActive?: () => boolean;
|
|
80
|
+
/**
|
|
81
|
+
* Optional callback used by the `GET /custom-field-definitions/:modelName` handler to expand
|
|
82
|
+
* the `entityIds` query parameter — typically to include ancestor entityIds the caller can
|
|
83
|
+
* see (e.g. partner-level contexts above the requested fleet). Receives the raw `entityIds`
|
|
84
|
+
* from the request (or `undefined` when not provided) and returns the list to filter by.
|
|
85
|
+
*
|
|
86
|
+
* Only invoked when provided; when omitted, the handler uses `entityIds` as-is.
|
|
87
|
+
*/
|
|
88
|
+
getEntityIdScope?: (entityIds: string[] | undefined) => Promise<string[] | undefined> | string[] | undefined;
|
|
56
89
|
}
|
|
57
90
|
//#endregion
|
|
58
91
|
export { CustomFieldOptions, ModelFetcher, Models };
|
package/dist/utils/init.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.cjs","names":["customFields","DataTypes","beforeFind","beforeBulkCreate","beforeBulkUpdate","beforeCreate","beforeUpdate","enrichResults","CustomFieldValue","customFieldsFilterScope","CUSTOM_FIELDS_SORT_SCOPE","customFieldsSortScope","CustomFieldDefinition","CustomValidator"],"sources":["../../src/utils/init.ts"],"sourcesContent":["import { DataTypes } from 'sequelize';\nimport type { ModelCtor } from 'sequelize-typescript';\nimport { customFields } from '@autofleet/common-types';\nimport { CUSTOM_FIELDS_SORT_SCOPE } from '@autofleet/common-types/lib/custom-fields';\nimport {\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\nimport {\n beforeFind,\n enrichResults,\n beforeBulkUpdate,\n beforeUpdate,\n beforeCreate,\n beforeBulkCreate,\n} from '../hooks';\nimport { customFieldsFilterScope } from '../scopes';\nimport logger from './logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from '../types';\nimport { customFieldsSortScope } from '../scopes/filter';\n\nconst { CUSTOM_FIELDS_FILTER_SCOPE } = customFields;\n\nexport const addHooks = (\n models: Models[],\n getModel: ModelFetcher,\n sadotOptions:
|
|
1
|
+
{"version":3,"file":"init.cjs","names":["customFields","DataTypes","beforeFind","beforeBulkCreate","beforeBulkUpdate","beforeCreate","beforeUpdate","enrichResults","CustomFieldValue","customFieldsFilterScope","CUSTOM_FIELDS_SORT_SCOPE","customFieldsSortScope","CustomFieldDefinition","CustomValidator"],"sources":["../../src/utils/init.ts"],"sourcesContent":["import { DataTypes } from 'sequelize';\nimport type { ModelCtor } from 'sequelize-typescript';\nimport { customFields } from '@autofleet/common-types';\nimport { CUSTOM_FIELDS_SORT_SCOPE } from '@autofleet/common-types/lib/custom-fields';\nimport {\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\nimport {\n beforeFind,\n enrichResults,\n beforeBulkUpdate,\n beforeUpdate,\n beforeCreate,\n beforeBulkCreate,\n} from '../hooks';\nimport { customFieldsFilterScope } from '../scopes';\nimport logger from './logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from '../types';\nimport { customFieldsSortScope } from '../scopes/filter';\n\nconst { CUSTOM_FIELDS_FILTER_SCOPE } = customFields;\n\ntype AddHooksOptions = {\n useCustomFieldsEntries?: boolean;\n matPathManager?: CustomFieldOptions['matPathManager'];\n isMatPathActive?: CustomFieldOptions['isMatPathActive'];\n};\n\nexport const addHooks = (\n models: Models[],\n getModel: ModelFetcher,\n sadotOptions: AddHooksOptions = { useCustomFieldsEntries: false },\n): void => {\n models.forEach(async ({\n name, scopeAttributes, modelOptions, hasTypeId, getRequiredCustomFields,\n }) => {\n try {\n const model = getModel(name);\n if (!model) {\n logger.warn('sadot - tried to addHooks to a model that does not exist yet', {\n name,\n scopeAttributes,\n });\n return;\n }\n model.rawAttributes.customFields = {\n type: DataTypes.VIRTUAL,\n };\n model.refreshAttributes();\n\n const enrichOptions = {\n ...sadotOptions,\n hasTypeId: hasTypeId ?? false,\n getRequiredCustomFields,\n };\n\n // TODO: Uncomment after tests are passed\n // model.addHook('afterFind', workaround);\n model.addHook('beforeFind', 'sadot-beforeFind', beforeFind(scopeAttributes));\n model.addHook('beforeBulkCreate', 'sadot-beforeBulkCreate', beforeBulkCreate);\n model.addHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate', beforeBulkUpdate);\n model.addHook('beforeCreate', 'sadot-beforeCreate', beforeCreate(scopeAttributes, modelOptions, enrichOptions));\n model.addHook('beforeUpdate', 'sadot-beforeUpdate', beforeUpdate(scopeAttributes, modelOptions, enrichOptions));\n model.addHook('afterFind', 'sadot-afterFind', enrichResults(name, scopeAttributes, 'afterFind', modelOptions, enrichOptions));\n model.addHook('afterUpdate', 'sadot-afterUpdate', enrichResults(name, scopeAttributes, undefined, modelOptions, enrichOptions));\n model.addHook('afterCreate', 'sadot-afterCreate', enrichResults(name, scopeAttributes, undefined, modelOptions, enrichOptions));\n } catch (e) {\n logger.error(`Could not add custom fields hook to model ${name}. `, e);\n }\n });\n};\n\nexport const removeHooks = (models: Models[], getModel: ModelFetcher): void => {\n models.forEach(async ({ name }) => {\n try {\n const model = getModel(name);\n if (!model) return;\n if (model.rawAttributes.customFields) {\n delete model.rawAttributes.customFields;\n model.refreshAttributes();\n }\n // model.removeHook('afterFind', 'sadot-workaround');\n model.removeHook('beforeFind', 'sadot-beforeFind');\n model.removeHook('beforeBulkCreate', 'sadot-beforeBulkCreate');\n model.removeHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate');\n model.removeHook('beforeCreate', 'sadot-beforeCreate');\n model.removeHook('beforeUpdate', 'sadot-beforeUpdate');\n model.removeHook('afterFind', 'sadot-afterFind');\n model.removeHook('afterUpdate', 'sadot-afterUpdate');\n } catch (e) {\n logger.error(`Could not add custom fields hook to model ${name}. `, e);\n }\n });\n};\n\n/**\n * Necessary associations for the {@link customFieldsFilterScope} scope\n */\nconst addAssociations = (model: ModelCtor, modelName: string, options: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>): void => {\n if (options?.useCustomFieldsEntries) return;\n model.hasMany(CustomFieldValue, { foreignKey: 'modelId', as: 'customFieldValue' });\n // TBC: maybe can be removed\n CustomFieldValue.belongsTo(model, { foreignKey: 'modelId', as: modelName });\n};\n\nexport const addScopes = (models: Models[], getModel: ModelFetcher, options: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false }): void => {\n models.forEach(async ({ name, scopeAttributes }) => {\n try {\n const model = getModel(name);\n if (!model) {\n logger.warn('sadot - tried to addScopes to a model that does not exist yet', {\n name,\n scopeAttributes,\n });\n return;\n }\n // Necessary associations for the filtering scope\n addAssociations(model, name, options);\n // Add filter scope\n model.addScope(CUSTOM_FIELDS_FILTER_SCOPE, customFieldsFilterScope(name, options));\n model.addScope(CUSTOM_FIELDS_SORT_SCOPE, customFieldsSortScope(name, options));\n } catch (e) {\n logger.error(`Could not add custom fields scopes to model ${name}. `, e);\n }\n });\n};\n\nexport const applyCustomAssociation = (models: Models[]): void => {\n models.forEach(({ modelOptions }) => {\n modelOptions?.customAssociation?.(CustomFieldDefinition);\n modelOptions?.customAssociation?.(CustomValidator);\n });\n};\n"],"mappings":"6jBAsBA,KAAM,CAAE,8BAA+BA,EAAAA,aAQ1B,GACX,EACA,EACA,EAAgC,CAAE,uBAAwB,GAAO,GACxD,CACT,EAAO,QAAQ,MAAO,CACpB,OAAM,kBAAiB,eAAc,YAAW,6BAC5C,CACJ,GAAI,CACF,IAAM,EAAQ,EAAS,EAAK,CAC5B,GAAI,CAAC,EAAO,CACV,EAAA,QAAO,KAAK,+DAAgE,CAC1E,OACA,kBACD,CAAC,CACF,OAEF,EAAM,cAAc,aAAe,CACjC,KAAMC,EAAAA,UAAU,QACjB,CACD,EAAM,mBAAmB,CAEzB,IAAM,EAAgB,CACpB,GAAG,EACH,UAAW,GAAa,GACxB,0BACD,CAID,EAAM,QAAQ,aAAc,mBAAoBC,EAAAA,WAAW,EAAgB,CAAC,CAC5E,EAAM,QAAQ,mBAAoB,yBAA0BC,EAAAA,iBAAiB,CAC7E,EAAM,QAAQ,mBAAoB,yBAA0BC,EAAAA,iBAAiB,CAC7E,EAAM,QAAQ,eAAgB,qBAAsBC,EAAAA,aAAa,EAAiB,EAAc,EAAc,CAAC,CAC/G,EAAM,QAAQ,eAAgB,qBAAsBC,EAAAA,aAAa,EAAiB,EAAc,EAAc,CAAC,CAC/G,EAAM,QAA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ACD,CAAC,CACF,OAGF,EAAgB,EAAO,EAAM,EAAQ,CAErC,EAAM,SAAS,EAA4BC,EAAAA,wBAAwB,EAAM,EAAQ,CAAC,CAClF,EAAM,SAASC,EAAAA,yBAA0BC,EAAAA,sBAAsB,EAAM,EAAQ,CAAC,OACvE,EAAG,CACV,EAAA,QAAO,MAAM,+CAA+C,EAAK,IAAK,EAAE,GAE1E,EAGS,EAA0B,GAA2B,CAChE,EAAO,SAAS,CAAE,kBAAmB,CACnC,GAAc,oBAAoBC,EAAAA,QAAsB,CACxD,GAAc,oBAAoBC,EAAAA,QAAgB,EAClD"}
|
package/dist/utils/init.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","names":["enrichResults","CustomFieldValue","CustomFieldDefinition","CustomValidator"],"sources":["../../src/utils/init.ts"],"sourcesContent":["import { DataTypes } from 'sequelize';\nimport type { ModelCtor } from 'sequelize-typescript';\nimport { customFields } from '@autofleet/common-types';\nimport { CUSTOM_FIELDS_SORT_SCOPE } from '@autofleet/common-types/lib/custom-fields';\nimport {\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\nimport {\n beforeFind,\n enrichResults,\n beforeBulkUpdate,\n beforeUpdate,\n beforeCreate,\n beforeBulkCreate,\n} from '../hooks';\nimport { customFieldsFilterScope } from '../scopes';\nimport logger from './logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from '../types';\nimport { customFieldsSortScope } from '../scopes/filter';\n\nconst { CUSTOM_FIELDS_FILTER_SCOPE } = customFields;\n\nexport const addHooks = (\n models: Models[],\n getModel: ModelFetcher,\n sadotOptions:
|
|
1
|
+
{"version":3,"file":"init.js","names":["enrichResults","CustomFieldValue","CustomFieldDefinition","CustomValidator"],"sources":["../../src/utils/init.ts"],"sourcesContent":["import { DataTypes } from 'sequelize';\nimport type { ModelCtor } from 'sequelize-typescript';\nimport { customFields } from '@autofleet/common-types';\nimport { CUSTOM_FIELDS_SORT_SCOPE } from '@autofleet/common-types/lib/custom-fields';\nimport {\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\nimport {\n beforeFind,\n enrichResults,\n beforeBulkUpdate,\n beforeUpdate,\n beforeCreate,\n beforeBulkCreate,\n} from '../hooks';\nimport { customFieldsFilterScope } from '../scopes';\nimport logger from './logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from '../types';\nimport { customFieldsSortScope } from '../scopes/filter';\n\nconst { CUSTOM_FIELDS_FILTER_SCOPE } = customFields;\n\ntype AddHooksOptions = {\n useCustomFieldsEntries?: boolean;\n matPathManager?: CustomFieldOptions['matPathManager'];\n isMatPathActive?: CustomFieldOptions['isMatPathActive'];\n};\n\nexport const addHooks = (\n models: Models[],\n getModel: ModelFetcher,\n sadotOptions: AddHooksOptions = { useCustomFieldsEntries: false },\n): void => {\n models.forEach(async ({\n name, scopeAttributes, modelOptions, hasTypeId, getRequiredCustomFields,\n }) => {\n try {\n const model = getModel(name);\n if (!model) {\n logger.warn('sadot - tried to addHooks to a model that does not exist yet', {\n name,\n scopeAttributes,\n });\n return;\n }\n model.rawAttributes.customFields = {\n type: DataTypes.VIRTUAL,\n };\n model.refreshAttributes();\n\n const enrichOptions = {\n ...sadotOptions,\n hasTypeId: hasTypeId ?? false,\n getRequiredCustomFields,\n };\n\n // TODO: Uncomment after tests are passed\n // model.addHook('afterFind', workaround);\n model.addHook('beforeFind', 'sadot-beforeFind', beforeFind(scopeAttributes));\n model.addHook('beforeBulkCreate', 'sadot-beforeBulkCreate', beforeBulkCreate);\n model.addHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate', beforeBulkUpdate);\n model.addHook('beforeCreate', 'sadot-beforeCreate', beforeCreate(scopeAttributes, modelOptions, enrichOptions));\n model.addHook('beforeUpdate', 'sadot-beforeUpdate', beforeUpdate(scopeAttributes, modelOptions, enrichOptions));\n model.addHook('afterFind', 'sadot-afterFind', enrichResults(name, scopeAttributes, 'afterFind', modelOptions, enrichOptions));\n model.addHook('afterUpdate', 'sadot-afterUpdate', enrichResults(name, scopeAttributes, undefined, modelOptions, enrichOptions));\n model.addHook('afterCreate', 'sadot-afterCreate', enrichResults(name, scopeAttributes, undefined, modelOptions, enrichOptions));\n } catch (e) {\n logger.error(`Could not add custom fields hook to model ${name}. `, e);\n }\n });\n};\n\nexport const removeHooks = (models: Models[], getModel: ModelFetcher): void => {\n models.forEach(async ({ name }) => {\n try {\n const model = getModel(name);\n if (!model) return;\n if (model.rawAttributes.customFields) {\n delete model.rawAttributes.customFields;\n model.refreshAttributes();\n }\n // model.removeHook('afterFind', 'sadot-workaround');\n model.removeHook('beforeFind', 'sadot-beforeFind');\n model.removeHook('beforeBulkCreate', 'sadot-beforeBulkCreate');\n model.removeHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate');\n model.removeHook('beforeCreate', 'sadot-beforeCreate');\n model.removeHook('beforeUpdate', 'sadot-beforeUpdate');\n model.removeHook('afterFind', 'sadot-afterFind');\n model.removeHook('afterUpdate', 'sadot-afterUpdate');\n } catch (e) {\n logger.error(`Could not add custom fields hook to model ${name}. `, e);\n }\n });\n};\n\n/**\n * Necessary associations for the {@link customFieldsFilterScope} scope\n */\nconst addAssociations = (model: ModelCtor, modelName: string, options: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>): void => {\n if (options?.useCustomFieldsEntries) return;\n model.hasMany(CustomFieldValue, { foreignKey: 'modelId', as: 'customFieldValue' });\n // TBC: maybe can be removed\n CustomFieldValue.belongsTo(model, { foreignKey: 'modelId', as: modelName });\n};\n\nexport const addScopes = (models: Models[], getModel: ModelFetcher, options: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false }): void => {\n models.forEach(async ({ name, scopeAttributes }) => {\n try {\n const model = getModel(name);\n if (!model) {\n logger.warn('sadot - tried to addScopes to a model that does not exist yet', {\n name,\n scopeAttributes,\n });\n return;\n }\n // Necessary associations for the filtering scope\n addAssociations(model, name, options);\n // Add filter scope\n model.addScope(CUSTOM_FIELDS_FILTER_SCOPE, customFieldsFilterScope(name, options));\n model.addScope(CUSTOM_FIELDS_SORT_SCOPE, customFieldsSortScope(name, options));\n } catch (e) {\n logger.error(`Could not add custom fields scopes to model ${name}. `, e);\n }\n });\n};\n\nexport const applyCustomAssociation = (models: Models[]): void => {\n models.forEach(({ modelOptions }) => {\n modelOptions?.customAssociation?.(CustomFieldDefinition);\n modelOptions?.customAssociation?.(CustomValidator);\n });\n};\n"],"mappings":"ssBAsBA,KAAM,CAAE,8BAA+B,EAQ1B,GACX,EACA,EACA,EAAgC,CAAE,uBAAwB,GAAO,GACxD,CACT,EAAO,QAAQ,MAAO,CACpB,OAAM,kBAAiB,eAAc,YAAW,6BAC5C,CACJ,GAAI,CACF,IAAM,EAAQ,EAAS,EAAK,CAC5B,GAAI,CAAC,EAAO,CACV,EAAO,KAAK,+DAAgE,CAC1E,OACA,kBACD,CAAC,CACF,OAEF,EAAM,cAAc,aAAe,CACjC,KAAM,EAAU,QACjB,CACD,EAAM,mBAAmB,CAEzB,IAAM,EAAgB,CACpB,GAAG,EACH,UAAW,GAAa,GACxB,0BACD,CAID,EAAM,QAAQ,aAAc,mBAAoB,EAAW,EAAgB,CAAC,CAC5E,EAAM,QAAQ,mBAAoB,yBAA0B,EAAiB,CAC7E,EAAM,QAAQ,mBAAoB,yBAA0B,EAAiB,CAC7E,EAAM,QAAQ,eAAgB,qBAAsB,EAAa,EAAiB,EAAc,EAAc,CAAC,CAC/G,EAAM,QAAQ,eAAgB,qBAAsB,EAAa,EAAiB,EAAc,EAAc,CAAC,CAC/G,EAAM,QAAQ,YAAa,kBAAmBA,EAAc,EAAM,EAAiB,YAAa,EAAc,EAAc,CAAC,CAC7H,EAAM,QAAQ,cAAe,oBAAqBA,EAAc,EAAM,EAAiB,IAAA,GAAW,EAAc,EAAc,CAAC,CAC/H,EAAM,QAAQ,cAAe,oBAAqBA,EAAc,EAAM,EAAiB,IAAA,GAAW,EAAc,EAAc,CAAC,OACxH,EA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CACxD,GAAc,oBAAoBC,EAAgB,EAClD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@autofleet/sadot",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.21-beta-e58014c3.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -45,17 +45,17 @@
|
|
|
45
45
|
"reflect-metadata": "^0.1.13",
|
|
46
46
|
"sequelize": "^6.37.7",
|
|
47
47
|
"sequelize-typescript": "^2.1.6",
|
|
48
|
-
"@autofleet/events": "^5.3.
|
|
48
|
+
"@autofleet/events": "^5.3.10"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@types/express": "^4.17.17",
|
|
52
52
|
"express": "^4.21.2",
|
|
53
53
|
"npm-watch": "^0.11.0",
|
|
54
54
|
"supertest": "^7.0.0",
|
|
55
|
-
"@autofleet/
|
|
56
|
-
"@autofleet/
|
|
57
|
-
"@autofleet/
|
|
58
|
-
"@autofleet/zehut": "^4.12.
|
|
55
|
+
"@autofleet/node-common": "^4.3.10",
|
|
56
|
+
"@autofleet/errors": "^3.1.50",
|
|
57
|
+
"@autofleet/logger": "^4.3.5",
|
|
58
|
+
"@autofleet/zehut": "^4.12.3"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
61
|
"@autofleet/errors": "^3",
|