@autofleet/sadot 1.0.7 → 1.0.9
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/index.cjs +46 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +255 -8
- package/dist/index.d.ts +255 -8
- package/dist/index.js +46 -1
- package/dist/index.js.map +1 -1
- package/package.json +16 -4
- package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorate.cjs +0 -1
- package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorate.js +0 -1
- package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorateMetadata.cjs +0 -1
- package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorateMetadata.js +0 -1
- package/dist/_virtual/rolldown_runtime.cjs +0 -1
- package/dist/api/index.cjs +0 -2
- package/dist/api/index.cjs.map +0 -1
- package/dist/api/index.js +0 -2
- package/dist/api/index.js.map +0 -1
- package/dist/api/v1/definition/index.cjs +0 -2
- package/dist/api/v1/definition/index.cjs.map +0 -1
- package/dist/api/v1/definition/index.js +0 -2
- package/dist/api/v1/definition/index.js.map +0 -1
- package/dist/api/v1/definition/validations.cjs +0 -2
- package/dist/api/v1/definition/validations.cjs.map +0 -1
- package/dist/api/v1/definition/validations.js +0 -2
- package/dist/api/v1/definition/validations.js.map +0 -1
- package/dist/api/v1/errors.cjs +0 -2
- package/dist/api/v1/errors.cjs.map +0 -1
- package/dist/api/v1/errors.js +0 -2
- package/dist/api/v1/errors.js.map +0 -1
- package/dist/api/v1/index.cjs +0 -2
- package/dist/api/v1/index.cjs.map +0 -1
- package/dist/api/v1/index.js +0 -2
- package/dist/api/v1/index.js.map +0 -1
- package/dist/api/v1/validator/index.cjs +0 -2
- package/dist/api/v1/validator/index.cjs.map +0 -1
- package/dist/api/v1/validator/index.js +0 -2
- package/dist/api/v1/validator/index.js.map +0 -1
- package/dist/api/v1/validator/validations.cjs +0 -2
- package/dist/api/v1/validator/validations.cjs.map +0 -1
- package/dist/api/v1/validator/validations.js +0 -2
- package/dist/api/v1/validator/validations.js.map +0 -1
- package/dist/errors/index.cjs +0 -3
- package/dist/errors/index.cjs.map +0 -1
- package/dist/errors/index.js +0 -3
- package/dist/errors/index.js.map +0 -1
- package/dist/events/index.cjs +0 -2
- package/dist/events/index.cjs.map +0 -1
- package/dist/events/index.js +0 -2
- package/dist/events/index.js.map +0 -1
- package/dist/hooks/enrich.cjs +0 -2
- package/dist/hooks/enrich.cjs.map +0 -1
- package/dist/hooks/enrich.js +0 -2
- package/dist/hooks/enrich.js.map +0 -1
- package/dist/hooks/find.cjs +0 -2
- package/dist/hooks/find.cjs.map +0 -1
- package/dist/hooks/find.js +0 -2
- package/dist/hooks/find.js.map +0 -1
- package/dist/hooks/hooks.cjs +0 -2
- package/dist/hooks/hooks.cjs.map +0 -1
- package/dist/hooks/hooks.js +0 -2
- package/dist/hooks/hooks.js.map +0 -1
- package/dist/hooks/index.cjs +0 -1
- package/dist/hooks/index.js +0 -1
- package/dist/hooks/utils/updateInstanceValues.cjs +0 -2
- package/dist/hooks/utils/updateInstanceValues.cjs.map +0 -1
- package/dist/hooks/utils/updateInstanceValues.js +0 -2
- package/dist/hooks/utils/updateInstanceValues.js.map +0 -1
- package/dist/models/CustomFieldDefinition.cjs +0 -2
- package/dist/models/CustomFieldDefinition.cjs.map +0 -1
- package/dist/models/CustomFieldDefinition.js +0 -2
- package/dist/models/CustomFieldDefinition.js.map +0 -1
- package/dist/models/CustomFieldEntries.cjs +0 -2
- package/dist/models/CustomFieldEntries.cjs.map +0 -1
- package/dist/models/CustomFieldEntries.js +0 -2
- package/dist/models/CustomFieldEntries.js.map +0 -1
- package/dist/models/CustomFieldValue.cjs +0 -2
- package/dist/models/CustomFieldValue.cjs.map +0 -1
- package/dist/models/CustomFieldValue.js +0 -2
- package/dist/models/CustomFieldValue.js.map +0 -1
- package/dist/models/CustomValidator.cjs +0 -2
- package/dist/models/CustomValidator.cjs.map +0 -1
- package/dist/models/CustomValidator.js +0 -2
- package/dist/models/CustomValidator.js.map +0 -1
- package/dist/models/index.cjs +0 -2
- package/dist/models/index.cjs.map +0 -1
- package/dist/models/index.js +0 -2
- package/dist/models/index.js.map +0 -1
- package/dist/models/tests/AssociatedTestModel.cjs +0 -2
- package/dist/models/tests/AssociatedTestModel.cjs.map +0 -1
- package/dist/models/tests/AssociatedTestModel.js +0 -2
- package/dist/models/tests/AssociatedTestModel.js.map +0 -1
- package/dist/models/tests/TestModel.cjs +0 -2
- package/dist/models/tests/TestModel.cjs.map +0 -1
- package/dist/models/tests/TestModel.js +0 -2
- package/dist/models/tests/TestModel.js.map +0 -1
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +0 -2
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +0 -1
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +0 -2
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +0 -1
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +0 -2
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +0 -1
- package/dist/models/tests/contextAwareModels/ContextTestModel.js +0 -2
- package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +0 -1
- package/dist/repository/definition.cjs +0 -2
- package/dist/repository/definition.cjs.map +0 -1
- package/dist/repository/definition.js +0 -2
- package/dist/repository/definition.js.map +0 -1
- package/dist/repository/entries.cjs +0 -2
- package/dist/repository/entries.cjs.map +0 -1
- package/dist/repository/entries.js +0 -2
- package/dist/repository/entries.js.map +0 -1
- package/dist/repository/utils/formatValues.cjs +0 -2
- package/dist/repository/utils/formatValues.cjs.map +0 -1
- package/dist/repository/utils/formatValues.js +0 -2
- package/dist/repository/utils/formatValues.js.map +0 -1
- package/dist/repository/validator.cjs +0 -2
- package/dist/repository/validator.cjs.map +0 -1
- package/dist/repository/validator.js +0 -2
- package/dist/repository/validator.js.map +0 -1
- package/dist/repository/value.cjs +0 -2
- package/dist/repository/value.cjs.map +0 -1
- package/dist/repository/value.js +0 -2
- package/dist/repository/value.js.map +0 -1
- package/dist/scopes/filter.cjs +0 -2
- package/dist/scopes/filter.cjs.map +0 -1
- package/dist/scopes/filter.d.cts +0 -23
- package/dist/scopes/filter.d.ts +0 -23
- package/dist/scopes/filter.js +0 -2
- package/dist/scopes/filter.js.map +0 -1
- package/dist/scopes/helpers/filter.helpers.cjs +0 -46
- package/dist/scopes/helpers/filter.helpers.cjs.map +0 -1
- package/dist/scopes/helpers/filter.helpers.d.cts +0 -17
- package/dist/scopes/helpers/filter.helpers.d.ts +0 -17
- package/dist/scopes/helpers/filter.helpers.js +0 -46
- package/dist/scopes/helpers/filter.helpers.js.map +0 -1
- package/dist/scopes/index.cjs +0 -1
- package/dist/scopes/index.js +0 -1
- package/dist/types/index.d.cts +0 -44
- package/dist/types/index.d.ts +0 -44
- package/dist/utils/constants/index.cjs +0 -2
- package/dist/utils/constants/index.cjs.map +0 -1
- package/dist/utils/constants/index.d.cts +0 -22
- package/dist/utils/constants/index.d.ts +0 -22
- package/dist/utils/constants/index.js +0 -2
- package/dist/utils/constants/index.js.map +0 -1
- package/dist/utils/db/index.cjs +0 -2
- package/dist/utils/db/index.cjs.map +0 -1
- package/dist/utils/db/index.js +0 -2
- package/dist/utils/db/index.js.map +0 -1
- package/dist/utils/helpers/index.cjs +0 -2
- package/dist/utils/helpers/index.cjs.map +0 -1
- package/dist/utils/helpers/index.d.cts +0 -31
- package/dist/utils/helpers/index.d.ts +0 -31
- package/dist/utils/helpers/index.js +0 -2
- package/dist/utils/helpers/index.js.map +0 -1
- package/dist/utils/init.cjs +0 -2
- package/dist/utils/init.cjs.map +0 -1
- package/dist/utils/init.js +0 -2
- package/dist/utils/init.js.map +0 -1
- package/dist/utils/logger/index.cjs +0 -2
- package/dist/utils/logger/index.cjs.map +0 -1
- package/dist/utils/logger/index.js +0 -2
- package/dist/utils/logger/index.js.map +0 -1
- package/dist/utils/scopeAttributes.cjs +0 -2
- package/dist/utils/scopeAttributes.cjs.map +0 -1
- package/dist/utils/scopeAttributes.js +0 -2
- package/dist/utils/scopeAttributes.js.map +0 -1
- package/dist/utils/validations/index.cjs +0 -2
- package/dist/utils/validations/index.cjs.map +0 -1
- package/dist/utils/validations/index.js +0 -2
- package/dist/utils/validations/index.js.map +0 -1
- package/dist/utils/validations/schema/custom-fields.cjs +0 -2
- package/dist/utils/validations/schema/custom-fields.cjs.map +0 -1
- package/dist/utils/validations/schema/custom-fields.d.cts +0 -7
- package/dist/utils/validations/schema/custom-fields.d.ts +0 -7
- package/dist/utils/validations/schema/custom-fields.js +0 -2
- package/dist/utils/validations/schema/custom-fields.js.map +0 -1
- package/dist/utils/validations/schema/validator-schema.cjs +0 -2
- package/dist/utils/validations/schema/validator-schema.cjs.map +0 -1
- package/dist/utils/validations/schema/validator-schema.js +0 -2
- package/dist/utils/validations/schema/validator-schema.js.map +0 -1
- package/dist/utils/validations/validators/index.cjs +0 -2
- package/dist/utils/validations/validators/index.cjs.map +0 -1
- package/dist/utils/validations/validators/index.js +0 -2
- package/dist/utils/validations/validators/index.js.map +0 -1
- package/dist/utils/validations/validators/select.validator.cjs +0 -2
- package/dist/utils/validations/validators/select.validator.cjs.map +0 -1
- package/dist/utils/validations/validators/select.validator.js +0 -2
- package/dist/utils/validations/validators/select.validator.js.map +0 -1
- package/dist/utils/validations/validators/status.validator.cjs +0 -2
- package/dist/utils/validations/validators/status.validator.cjs.map +0 -1
- package/dist/utils/validations/validators/status.validator.js +0 -2
- package/dist/utils/validations/validators/status.validator.js.map +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"../utils/logger/index.js";import{MissingDefinitionError as t}from"../errors/index.js";import{findAll as n}from"./definition.js";import r from"../models/CustomFieldEntries.js";import"../models/index.js";import{formatFunctions as i}from"./utils/formatValues.js";const a=async(e,t={})=>{let{transaction:n}=t;return r.findOne({where:{modelId:e},transaction:n})},o=async(e,t={})=>{let{transaction:n}=t;return r.findAll({where:{modelId:e},transaction:n})},s=async(a,o,s,c,l={})=>{let u=Object.keys(s);e.debug(`custom-fields: updating entries for ${o} ${a}`,{customFieldsNames:u,optionsKeys:l?Object.keys(l):null,customFields:s,identifiers:c});let{modelOptions:d,transaction:f}=l,p={modelType:o,name:u,...!l.modelOptions?.useEntityIdFromInclude&&{entityId:c}},m=await n(p,{withDisabled:!0,transaction:f,include:d.include?.(c)})??[],h=m.filter(e=>e.disabled);if(m.length!==u.length){e.warn(`custom-fields: missing definitions for ${o} ${a}`,{names:u,fieldDefinitions:m});let n=u.filter(e=>!m.some(t=>t.name===e));throw new t(n)}let g=h?.map(e=>e.name)||[],_=u.filter(e=>g.includes(e));_?.length>0&&e.warn(`custom-fields: trying to update disabled values: ${_.join(`, `)}`);let v=Object.fromEntries(m.map(e=>[e.name,e]));return Object.entries(s).filter(([e])=>i[v[e].fieldType]).forEach(([e,t])=>{let{fieldType:n}=v[e];s[e]=i[n](t)}),r.upsert({modelId:a,entityId:m[0].entityId,modelType:o,customFields:s},l)};export{a as findEntriesByModelId,o as findEntriesByModelIds,s as updateEntries};
|
|
2
|
-
//# sourceMappingURL=entries.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"entries.js","names":["CustomFieldEntries","where: WhereOptions","DefinitionRepo.findAll"],"sources":["../../src/repository/entries.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport type {\n FindOptions,\n Includeable,\n Transaction,\n WhereOptions,\n} from 'sequelize';\nimport { CustomFieldEntries } from '../models';\nimport type { ModelOptions } from '../types';\nimport logger from '../utils/logger';\nimport { MissingDefinitionError } from '../errors';\nimport * as DefinitionRepo from './definition';\nimport { formatFunctions } from './utils/formatValues';\n\ntype CustomFieldEntriesModelOptions = ModelOptions & { include?: Includeable, transaction?: Transaction };\n\nexport const findEntriesByModelId = async (modelId: string, options: CustomFieldEntriesModelOptions = {}): Promise<CustomFieldEntries | null> => {\n const { transaction } = options;\n return CustomFieldEntries.findOne({\n where: { modelId },\n transaction,\n });\n};\n\nexport const findEntriesByModelIds = async (modelIds: string[], options: CustomFieldEntriesModelOptions = {}): Promise<CustomFieldEntries[]> => {\n const { transaction } = options;\n return CustomFieldEntries.findAll({\n where: { modelId: modelIds },\n transaction,\n });\n};\n\nexport const updateEntries = async (\n modelId: string,\n modelType: string,\n customFields: Record<string, any>,\n identifiers: string[],\n options: FindOptions & { modelOptions?: ModelOptions } = {},\n): Promise<[CustomFieldEntries, boolean | null]> => {\n const customFieldsNames = Object.keys(customFields);\n logger.debug(`custom-fields: updating entries for ${modelType} ${modelId}`, {\n customFieldsNames,\n optionsKeys: options ? Object.keys(options) : null,\n customFields,\n identifiers,\n });\n const { modelOptions, transaction } = options;\n\n const where: WhereOptions = {\n modelType,\n name: customFieldsNames,\n ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions.include?.(identifiers) }) ?? [];\n\n const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);\n if (fieldDefinitions.length !== customFieldsNames.length) {\n logger.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names: customFieldsNames, fieldDefinitions });\n const missingDefinitions = customFieldsNames.filter((name) => !fieldDefinitions.some((def) => def.name === name));\n throw new MissingDefinitionError(missingDefinitions);\n }\n\n const disabledNames = disabledDefinitions?.map((def) => def.name) || [];\n const valuesWithDisabledDefinitions = customFieldsNames.filter((name) => disabledNames.includes(name));\n if (valuesWithDisabledDefinitions?.length > 0) {\n logger.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);\n }\n\n const definitionsByName = Object.fromEntries(fieldDefinitions.map((definition) => [definition.name, definition]));\n // If we need to format the value before we save it\n Object.entries(customFields)\n .filter(([definitionName]) => formatFunctions[definitionsByName[definitionName].fieldType])\n .forEach(([definitionName, value]) => {\n const { fieldType } = definitionsByName[definitionName];\n customFields[definitionName] = formatFunctions[fieldType](value);\n });\n\n return CustomFieldEntries.upsert(\n {\n modelId,\n entityId: fieldDefinitions[0].entityId,\n modelType,\n customFields,\n },\n options,\n );\n};\n"],"mappings":"kRAgBA,MAAa,EAAuB,MAAO,EAAiB,EAA0C,EAAE,GAAyC,CAC/I,GAAM,CAAE,eAAgB,EACxB,OAAOA,EAAmB,QAAQ,CAChC,MAAO,CAAE,UAAS,CAClB,cACD,CAAC,EAGS,EAAwB,MAAO,EAAoB,EAA0C,EAAE,GAAoC,CAC9I,GAAM,CAAE,eAAgB,EACxB,OAAOA,EAAmB,QAAQ,CAChC,MAAO,CAAE,QAAS,EAAU,CAC5B,cACD,CAAC,EAGS,EAAgB,MAC3B,EACA,EACA,EACA,EACA,EAAyD,EAAE,GACT,CAClD,IAAM,EAAoB,OAAO,KAAK,EAAa,CACnD,EAAO,MAAM,uCAAuC,EAAU,GAAG,IAAW,CAC1E,oBACA,YAAa,EAAU,OAAO,KAAK,EAAQ,CAAG,KAC9C,eACA,cACD,CAAC,CACF,GAAM,CAAE,eAAc,eAAgB,EAEhCC,EAAsB,CAC1B,YACA,KAAM,EACN,GAAI,CAAC,EAAQ,cAAc,wBAA0B,CAAE,SAAU,EAAa,CAC/E,CAEK,EAAmB,MAAMC,EAAuB,EAAO,CAAE,aAAc,GAAM,cAAa,QAAS,EAAa,UAAU,EAAY,CAAE,CAAC,EAAI,EAAE,CAE/I,EAAsB,EAAiB,OAAQ,GAAQ,EAAI,SAAS,CAC1E,GAAI,EAAiB,SAAW,EAAkB,OAAQ,CACxD,EAAO,KAAK,0CAA0C,EAAU,GAAG,IAAW,CAAE,MAAO,EAAmB,mBAAkB,CAAC,CAC7H,IAAM,EAAqB,EAAkB,OAAQ,GAAS,CAAC,EAAiB,KAAM,GAAQ,EAAI,OAAS,EAAK,CAAC,CACjH,MAAM,IAAI,EAAuB,EAAmB,CAGtD,IAAM,EAAgB,GAAqB,IAAK,GAAQ,EAAI,KAAK,EAAI,EAAE,CACjE,EAAgC,EAAkB,OAAQ,GAAS,EAAc,SAAS,EAAK,CAAC,CAClG,GAA+B,OAAS,GAC1C,EAAO,KAAK,oDAAoD,EAA8B,KAAK,KAAK,GAAG,CAG7G,IAAM,EAAoB,OAAO,YAAY,EAAiB,IAAK,GAAe,CAAC,EAAW,KAAM,EAAW,CAAC,CAAC,CASjH,OAPA,OAAO,QAAQ,EAAa,CACzB,QAAQ,CAAC,KAAoB,EAAgB,EAAkB,GAAgB,WAAW,CAC1F,SAAS,CAAC,EAAgB,KAAW,CACpC,GAAM,CAAE,aAAc,EAAkB,GACxC,EAAa,GAAkB,EAAgB,GAAW,EAAM,EAChE,CAEGF,EAAmB,OACxB,CACE,UACA,SAAU,EAAiB,GAAG,SAC9B,YACA,eACD,CACD,EACD"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../../utils/constants/index.cjs`),t={[e.CustomFieldDefinitionType.DATE]:e=>{if(e){let t=new Date(e);if(t.toString()===`Invalid Date`)throw Error(`Invalid date value: ${e}`);return t.toISOString()}return null}};exports.formatFunctions=t;
|
|
2
|
-
//# sourceMappingURL=formatValues.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"formatValues.cjs","names":["formatFunctions: Partial<Record<CustomFieldDefinitionType, (value: any) => string | null>>","CustomFieldDefinitionType"],"sources":["../../../src/repository/utils/formatValues.ts"],"sourcesContent":["import { CustomFieldDefinitionType } from '../../utils/constants';\n\nexport const formatFunctions: Partial<Record<CustomFieldDefinitionType, (value: any) => string | null>> = {\n [CustomFieldDefinitionType.DATE]: (value) => {\n if (value) {\n const date = new Date(value);\n if (date.toString() === 'Invalid Date') {\n throw new Error(`Invalid date value: ${value}`);\n }\n return date.toISOString();\n }\n return null;\n },\n};\n"],"mappings":"mDAEaA,EAA6F,EACvGC,EAAAA,0BAA0B,MAAQ,GAAU,CAC3C,GAAI,EAAO,CACT,IAAM,EAAO,IAAI,KAAK,EAAM,CAC5B,GAAI,EAAK,UAAU,GAAK,eACtB,MAAU,MAAM,uBAAuB,IAAQ,CAEjD,OAAO,EAAK,aAAa,CAE3B,OAAO,MAEV"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{CustomFieldDefinitionType as e}from"../../utils/constants/index.js";const t={[e.DATE]:e=>{if(e){let t=new Date(e);if(t.toString()===`Invalid Date`)throw Error(`Invalid date value: ${e}`);return t.toISOString()}return null}};export{t as formatFunctions};
|
|
2
|
-
//# sourceMappingURL=formatValues.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"formatValues.js","names":["formatFunctions: Partial<Record<CustomFieldDefinitionType, (value: any) => string | null>>"],"sources":["../../../src/repository/utils/formatValues.ts"],"sourcesContent":["import { CustomFieldDefinitionType } from '../../utils/constants';\n\nexport const formatFunctions: Partial<Record<CustomFieldDefinitionType, (value: any) => string | null>> = {\n [CustomFieldDefinitionType.DATE]: (value) => {\n if (value) {\n const date = new Date(value);\n if (date.toString() === 'Invalid Date') {\n throw new Error(`Invalid date value: ${value}`);\n }\n return date.toISOString();\n }\n return null;\n },\n};\n"],"mappings":"2EAEA,MAAaA,EAA6F,EACvG,EAA0B,MAAQ,GAAU,CAC3C,GAAI,EAAO,CACT,IAAM,EAAO,IAAI,KAAK,EAAM,CAC5B,GAAI,EAAK,UAAU,GAAK,eACtB,MAAU,MAAM,uBAAuB,IAAQ,CAEjD,OAAO,EAAK,aAAa,CAE3B,OAAO,MAEV"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../utils/logger/index.cjs`),t=require(`../models/CustomValidator.cjs`);require(`../models/index.cjs`);const n=async(n,r={})=>(e.default.debug(`custom-validator - create validator`),await t.default.create(n,r)),r=async(n={},r={})=>{e.default.debug(`custom-validator - find all validators`);let{transaction:i,withDisabled:a,include:o,attributes:s,raw:c}=r,l;return l=a?await t.default.unscoped().scope(`userScope`).findAll({where:n,transaction:i,include:o,attributes:s,raw:c}):await t.default.scope([`defaultScope`,`userScope`]).findAll({where:n,transaction:i,include:o,attributes:s,raw:c}),l},i=async(t,n,i={})=>(e.default.debug(`custom-validator - find all validators by model type`),r({modelType:t,...!i?.modelOptions?.useEntityIdFromInclude&&{entityId:n}},{...i,include:i?.modelOptions?.include?.(n)})),a=async(n,r,i)=>(e.default.debug(`custom-validator - update validator`),t.default.update(r,{where:{id:n},returning:!0,...i})),o=async(t,n)=>(e.default.debug(`custom-validator - disable validator`),a(t,{disabled:!0},n));exports.create=n,exports.disable=o,exports.findAll=r,exports.findAllByModelType=i,exports.update=a;
|
|
2
|
-
//# sourceMappingURL=validator.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validator.cjs","names":["CustomValidator"],"sources":["../../src/repository/validator.ts"],"sourcesContent":["import type { FindOptions, IncludeOptions, Transactionable } from 'sequelize';\nimport logger from '../utils/logger';\nimport { CustomValidator } from '../models';\nimport type { ModelOptions } from '../types';\n\nexport interface FindValidatorOptions extends Transactionable {\n withDisabled?: boolean;\n attributes?: string[];\n raw?: boolean;\n include?: IncludeOptions[];\n}\n\n// Make sure this interface is compatible with the Sequelize model\nexport interface ValidatorAttributes {\n entityId: string;\n entityType: string;\n modelType: string;\n schema: CustomValidator['schema'];\n disabled?: boolean;\n [key: string]: unknown; // Add index signature for Sequelize compatibility\n}\n\nexport const create = async (\n validatorAttributes: ValidatorAttributes,\n options: Transactionable = {},\n): Promise<CustomValidator> => {\n logger.debug('custom-validator - create validator');\n\n // Use unknown type to bypass TypeScript errors while maintaining compatibility\n const validator = await CustomValidator.create(validatorAttributes as Record<string, unknown>, options);\n\n return validator;\n};\n\nexport const findAll = async (\n where = {},\n options: FindOptions & {\n modelOptions?: ModelOptions,\n withDisabled?: boolean\n } = {},\n): Promise<CustomValidator[]> => {\n logger.debug('custom-validator - find all validators');\n\n const {\n transaction, withDisabled, include, attributes, raw,\n } = options;\n\n let validators;\n if (withDisabled) {\n // If withDisabled is true, use unscoped to ignore the default scope that filters disabled items\n // Apply the userScope separately to maintain permission filtering\n validators = await CustomValidator.unscoped().scope('userScope').findAll({\n where,\n transaction,\n include,\n attributes,\n raw,\n });\n } else {\n // Use defaultScope and userScope to filter both disabled and by permissions\n // The defaultScope keeps only non-disabled validators\n validators = await CustomValidator.scope(['defaultScope', 'userScope']).findAll({\n where,\n transaction,\n include,\n attributes,\n raw,\n });\n }\n\n return validators;\n};\n\nexport const findAllByModelType = async (\n modelType: string,\n entityId: string,\n options: FindOptions & {\n modelOptions?: ModelOptions,\n withDisabled?: boolean\n } = {},\n): Promise<CustomValidator[]> => {\n logger.debug('custom-validator - find all validators by model type');\n return findAll(\n {\n modelType,\n ...(!options?.modelOptions?.useEntityIdFromInclude && { entityId }),\n },\n {\n ...options,\n include: options?.modelOptions?.include?.(entityId),\n },\n );\n};\n\nexport const update = async (\n id: string,\n updates: Partial<ValidatorAttributes>,\n options?: Transactionable,\n): Promise<[number, CustomValidator[]]> => {\n logger.debug('custom-validator - update validator');\n\n return CustomValidator.update(\n updates,\n {\n where: { id },\n returning: true,\n ...options,\n },\n );\n};\n\nexport const disable = async (\n id: string,\n options?: Transactionable,\n): Promise<[number, CustomValidator[]]> => {\n logger.debug('custom-validator - disable validator');\n\n return update(id, { disabled: true }, options);\n};\n"],"mappings":"uHAsBA,MAAa,EAAS,MACpB,EACA,EAA2B,EAAE,IAE7B,EAAA,QAAO,MAAM,sCAAsC,CAGjC,MAAMA,EAAAA,QAAgB,OAAO,EAAgD,EAAQ,EAK5F,EAAU,MACrB,EAAQ,EAAE,CACV,EAGM,EAAE,GACuB,CAC/B,EAAA,QAAO,MAAM,yCAAyC,CAEtD,GAAM,CACJ,cAAa,eAAc,UAAS,aAAY,OAC9C,EAEA,EAuBJ,MAtBA,CAaE,EAbE,EAGW,MAAMA,EAAAA,QAAgB,UAAU,CAAC,MAAM,YAAY,CAAC,QAAQ,CACvE,QACA,cACA,UACA,aACA,MACD,CAAC,CAIW,MAAMA,EAAAA,QAAgB,MAAM,CAAC,eAAgB,YAAY,CAAC,CAAC,QAAQ,CAC9E,QACA,cACA,UACA,aACA,MACD,CAAC,CAGG,GAGI,EAAqB,MAChC,EACA,EACA,EAGI,EAAE,IAEN,EAAA,QAAO,MAAM,uDAAuD,CAC7D,EACL,CACE,YACA,GAAI,CAAC,GAAS,cAAc,wBAA0B,CAAE,WAAU,CACnE,CACD,CACE,GAAG,EACH,QAAS,GAAS,cAAc,UAAU,EAAS,CACpD,CACF,EAGU,EAAS,MACpB,EACA,EACA,KAEA,EAAA,QAAO,MAAM,sCAAsC,CAE5CA,EAAAA,QAAgB,OACrB,EACA,CACE,MAAO,CAAE,KAAI,CACb,UAAW,GACX,GAAG,EACJ,CACF,EAGU,EAAU,MACrB,EACA,KAEA,EAAA,QAAO,MAAM,uCAAuC,CAE7C,EAAO,EAAI,CAAE,SAAU,GAAM,CAAE,EAAQ"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"../utils/logger/index.js";import t from"../models/CustomValidator.js";import"../models/index.js";const n=async(n,r={})=>(e.debug(`custom-validator - create validator`),await t.create(n,r)),r=async(n={},r={})=>{e.debug(`custom-validator - find all validators`);let{transaction:i,withDisabled:a,include:o,attributes:s,raw:c}=r,l;return l=a?await t.unscoped().scope(`userScope`).findAll({where:n,transaction:i,include:o,attributes:s,raw:c}):await t.scope([`defaultScope`,`userScope`]).findAll({where:n,transaction:i,include:o,attributes:s,raw:c}),l},i=async(t,n,i={})=>(e.debug(`custom-validator - find all validators by model type`),r({modelType:t,...!i?.modelOptions?.useEntityIdFromInclude&&{entityId:n}},{...i,include:i?.modelOptions?.include?.(n)})),a=async(n,r,i)=>(e.debug(`custom-validator - update validator`),t.update(r,{where:{id:n},returning:!0,...i})),o=async(t,n)=>(e.debug(`custom-validator - disable validator`),a(t,{disabled:!0},n));export{n as create,o as disable,r as findAll,i as findAllByModelType,a as update};
|
|
2
|
-
//# sourceMappingURL=validator.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validator.js","names":["CustomValidator"],"sources":["../../src/repository/validator.ts"],"sourcesContent":["import type { FindOptions, IncludeOptions, Transactionable } from 'sequelize';\nimport logger from '../utils/logger';\nimport { CustomValidator } from '../models';\nimport type { ModelOptions } from '../types';\n\nexport interface FindValidatorOptions extends Transactionable {\n withDisabled?: boolean;\n attributes?: string[];\n raw?: boolean;\n include?: IncludeOptions[];\n}\n\n// Make sure this interface is compatible with the Sequelize model\nexport interface ValidatorAttributes {\n entityId: string;\n entityType: string;\n modelType: string;\n schema: CustomValidator['schema'];\n disabled?: boolean;\n [key: string]: unknown; // Add index signature for Sequelize compatibility\n}\n\nexport const create = async (\n validatorAttributes: ValidatorAttributes,\n options: Transactionable = {},\n): Promise<CustomValidator> => {\n logger.debug('custom-validator - create validator');\n\n // Use unknown type to bypass TypeScript errors while maintaining compatibility\n const validator = await CustomValidator.create(validatorAttributes as Record<string, unknown>, options);\n\n return validator;\n};\n\nexport const findAll = async (\n where = {},\n options: FindOptions & {\n modelOptions?: ModelOptions,\n withDisabled?: boolean\n } = {},\n): Promise<CustomValidator[]> => {\n logger.debug('custom-validator - find all validators');\n\n const {\n transaction, withDisabled, include, attributes, raw,\n } = options;\n\n let validators;\n if (withDisabled) {\n // If withDisabled is true, use unscoped to ignore the default scope that filters disabled items\n // Apply the userScope separately to maintain permission filtering\n validators = await CustomValidator.unscoped().scope('userScope').findAll({\n where,\n transaction,\n include,\n attributes,\n raw,\n });\n } else {\n // Use defaultScope and userScope to filter both disabled and by permissions\n // The defaultScope keeps only non-disabled validators\n validators = await CustomValidator.scope(['defaultScope', 'userScope']).findAll({\n where,\n transaction,\n include,\n attributes,\n raw,\n });\n }\n\n return validators;\n};\n\nexport const findAllByModelType = async (\n modelType: string,\n entityId: string,\n options: FindOptions & {\n modelOptions?: ModelOptions,\n withDisabled?: boolean\n } = {},\n): Promise<CustomValidator[]> => {\n logger.debug('custom-validator - find all validators by model type');\n return findAll(\n {\n modelType,\n ...(!options?.modelOptions?.useEntityIdFromInclude && { entityId }),\n },\n {\n ...options,\n include: options?.modelOptions?.include?.(entityId),\n },\n );\n};\n\nexport const update = async (\n id: string,\n updates: Partial<ValidatorAttributes>,\n options?: Transactionable,\n): Promise<[number, CustomValidator[]]> => {\n logger.debug('custom-validator - update validator');\n\n return CustomValidator.update(\n updates,\n {\n where: { id },\n returning: true,\n ...options,\n },\n );\n};\n\nexport const disable = async (\n id: string,\n options?: Transactionable,\n): Promise<[number, CustomValidator[]]> => {\n logger.debug('custom-validator - disable validator');\n\n return update(id, { disabled: true }, options);\n};\n"],"mappings":"+GAsBA,MAAa,EAAS,MACpB,EACA,EAA2B,EAAE,IAE7B,EAAO,MAAM,sCAAsC,CAGjC,MAAMA,EAAgB,OAAO,EAAgD,EAAQ,EAK5F,EAAU,MACrB,EAAQ,EAAE,CACV,EAGM,EAAE,GACuB,CAC/B,EAAO,MAAM,yCAAyC,CAEtD,GAAM,CACJ,cAAa,eAAc,UAAS,aAAY,OAC9C,EAEA,EAuBJ,MAtBA,CAaE,EAbE,EAGW,MAAMA,EAAgB,UAAU,CAAC,MAAM,YAAY,CAAC,QAAQ,CACvE,QACA,cACA,UACA,aACA,MACD,CAAC,CAIW,MAAMA,EAAgB,MAAM,CAAC,eAAgB,YAAY,CAAC,CAAC,QAAQ,CAC9E,QACA,cACA,UACA,aACA,MACD,CAAC,CAGG,GAGI,EAAqB,MAChC,EACA,EACA,EAGI,EAAE,IAEN,EAAO,MAAM,uDAAuD,CAC7D,EACL,CACE,YACA,GAAI,CAAC,GAAS,cAAc,wBAA0B,CAAE,WAAU,CACnE,CACD,CACE,GAAG,EACH,QAAS,GAAS,cAAc,UAAU,EAAS,CACpD,CACF,EAGU,EAAS,MACpB,EACA,EACA,KAEA,EAAO,MAAM,sCAAsC,CAE5CA,EAAgB,OACrB,EACA,CACE,MAAO,CAAE,KAAI,CACb,UAAW,GACX,GAAG,EACJ,CACF,EAGU,EAAU,MACrB,EACA,KAEA,EAAO,MAAM,uCAAuC,CAE7C,EAAO,EAAI,CAAE,SAAU,GAAM,CAAE,EAAQ"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../utils/logger/index.cjs`),t=require(`../errors/index.cjs`),n=require(`./definition.cjs`),r=require(`../models/CustomFieldValue.cjs`);require(`../models/index.cjs`);const i=require(`./utils/formatValues.cjs`),a=async(e,t)=>{let{transaction:n}=t;return r.default.findAll({where:{modelId:e},transaction:n,raw:!0,nest:!0})},o=async(a,o,s,c,l={})=>{let u=Object.keys(c);e.default.debug(`custom-fields: updating values for ${a} ${o}`,{names:u,optionsKeys:l?Object.keys(l):null,valuesToUpdate:c,identifiers:s});let{modelOptions:d,transaction:f}=l,p={modelType:a,name:u,...!l.modelOptions?.useEntityIdFromInclude&&{entityId:s}},m=await n.findAll(p,{withDisabled:!0,transaction:f,include:d.include?.(s)})??[],h=m.filter(e=>e.disabled);if(m.length!==u.length){e.default.warn(`custom-fields: missing definitions for ${a} ${o}`,{names:u,fieldDefinitions:m});let n=u.filter(e=>!m.some(t=>t.name===e));throw new t.MissingDefinitionError(n)}let g=h?.map(e=>e.name)||[],_=u.filter(e=>g.includes(e));_?.length>0&&e.default.warn(`custom-fields: trying to update disabled values: ${_.join(`, `)}`);let v=u.map(e=>{let t=m.find(t=>t.name===e),n=i.formatFunctions[t.fieldType],r=n?n(c[e]):c[e];return{modelId:o,updatedAt:new Date,customFieldDefinitionId:t.id,value:r===void 0?t.defaultValue:r}});return Promise.all(v.map(async e=>{let[t]=await r.default.upsert(e,{transaction:l.transaction});return t}))};exports.findValuesByModelIds=a,exports.updateValues=o;
|
|
2
|
-
//# sourceMappingURL=value.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"value.cjs","names":["CustomFieldValue","where: WhereOptions","MissingDefinitionError","values: CreateCustomFieldValue[]","formatFunctions"],"sources":["../../src/repository/value.ts"],"sourcesContent":["import type { FindOptions, Transactionable, WhereOptions } from 'sequelize';\nimport { CustomFieldValue, CustomFieldDefinition } from '../models';\nimport * as DefinitionRepo from './definition';\nimport type { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';\nimport logger from '../utils/logger';\nimport { MissingDefinitionError } from '../errors';\nimport type { ModelOptions } from '../types';\nimport { formatFunctions } from './utils/formatValues';\n\nexport const findByModelIdAndDefinition = async (modelId: string, customFieldDefinitionId: string): Promise<CustomFieldValue[]> =>\n CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [CustomFieldDefinition] });\n\nexport const create = async (data: CreateCustomFieldValue, withAssociations = false): Promise<CustomFieldValue> => {\n const created = await CustomFieldValue.create(data);\n if (withAssociations) {\n const createdWithAssociations = await findByModelIdAndDefinition(created.modelId, created.customFieldDefinitionId);\n return createdWithAssociations?.[0];\n }\n return created;\n};\n\nexport const findAllValues = async (): Promise<CustomFieldValue[]> => CustomFieldValue.findAll({ include: [CustomFieldDefinition] });\n/**\n * Get all values for model instance id (with their definitions)\n * @param modelId\n * @returns CustomFieldValue[]\n */\nexport const findValuesByModelId = async (modelId: string): Promise<CustomFieldValue[]> => CustomFieldValue.findAll({ where: { modelId }, include: [CustomFieldDefinition] });\n\n/**\n* Retrieves custom field values for given model IDs\n* @param modelIds - An array of model IDs to query custom field values for.\n* @param options - Optional configuration object.\n*/\nexport const findValuesByModelIds = async (modelIds: string[], options?: Transactionable): Promise<CustomFieldValue[]> => {\n const { transaction } = options;\n return CustomFieldValue.findAll({\n where: { modelId: modelIds },\n transaction,\n raw: true,\n nest: true,\n });\n};\n\n/**\n * Try to update custom field values for a model instance.\n * Create new value record if not exists, but fails if value's definition not exist.\n * Return the updated values\n */\nexport const updateValues = async (\n modelType: string,\n modelId: string,\n identifiers: string[],\n valuesToUpdate: ValuesToUpdate,\n options: FindOptions & { modelOptions?: ModelOptions } = {},\n): Promise<CustomFieldValue[]> => {\n const names = Object.keys(valuesToUpdate);\n logger.debug(`custom-fields: updating values for ${modelType} ${modelId}`, {\n names,\n optionsKeys: options ? Object.keys(options) : null,\n valuesToUpdate,\n identifiers,\n });\n const { modelOptions, transaction } = options;\n\n const where: WhereOptions = {\n modelType,\n name: names,\n ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions.include?.(identifiers) }) ?? [];\n\n const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);\n if (fieldDefinitions.length !== names.length) {\n logger.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });\n const missingDefinitions = names.filter((name) => !fieldDefinitions.some((def) => def.name === name));\n throw new MissingDefinitionError(missingDefinitions);\n }\n\n const disabledNames = disabledDefinitions?.map((def) => def.name) || [];\n const valuesWithDisabledDefinitions = names.filter((name) => disabledNames.includes(name));\n if (valuesWithDisabledDefinitions?.length > 0) {\n logger.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);\n }\n\n const values: CreateCustomFieldValue[] = names.map((name) => {\n const fieldDefinition = fieldDefinitions.find((def) => def.name === name);\n const formatFunction = formatFunctions[fieldDefinition.fieldType];\n const value = formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name];\n return {\n modelId,\n updatedAt: new Date(),\n customFieldDefinitionId: fieldDefinition.id,\n value: value !== undefined ? value : fieldDefinition.defaultValue,\n };\n });\n\n return Promise.all(values.map(async (value) => {\n const [cfv] = await CustomFieldValue.upsert(value, {\n transaction: options.transaction,\n });\n return cfv;\n }));\n};\n\nexport const deleteValue = (\n id: string,\n options: any = {},\n): Promise<any> => CustomFieldValue.update(\n { deletedAt: new Date() },\n {\n where: { id },\n transaction: options.transaction,\n },\n);\n"],"mappings":"mOAkCa,EAAuB,MAAO,EAAoB,IAA2D,CACxH,GAAM,CAAE,eAAgB,EACxB,OAAOA,EAAAA,QAAiB,QAAQ,CAC9B,MAAO,CAAE,QAAS,EAAU,CAC5B,cACA,IAAK,GACL,KAAM,GACP,CAAC,EAQS,EAAe,MA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B,EACD,CAEF,OAAO,QAAQ,IAAI,EAAO,IAAI,KAAO,IAAU,CAC7C,GAAM,CAAC,GAAO,MAAMJ,EAAAA,QAAiB,OAAO,EAAO,CACjD,YAAa,EAAQ,YACtB,CAAC,CACF,OAAO,GACP,CAAC"}
|
package/dist/repository/value.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"../utils/logger/index.js";import{MissingDefinitionError as t}from"../errors/index.js";import{findAll as n}from"./definition.js";import r from"../models/CustomFieldValue.js";import"../models/index.js";import{formatFunctions as i}from"./utils/formatValues.js";const a=async(e,t)=>{let{transaction:n}=t;return r.findAll({where:{modelId:e},transaction:n,raw:!0,nest:!0})},o=async(a,o,s,c,l={})=>{let u=Object.keys(c);e.debug(`custom-fields: updating values for ${a} ${o}`,{names:u,optionsKeys:l?Object.keys(l):null,valuesToUpdate:c,identifiers:s});let{modelOptions:d,transaction:f}=l,p={modelType:a,name:u,...!l.modelOptions?.useEntityIdFromInclude&&{entityId:s}},m=await n(p,{withDisabled:!0,transaction:f,include:d.include?.(s)})??[],h=m.filter(e=>e.disabled);if(m.length!==u.length){e.warn(`custom-fields: missing definitions for ${a} ${o}`,{names:u,fieldDefinitions:m});let n=u.filter(e=>!m.some(t=>t.name===e));throw new t(n)}let g=h?.map(e=>e.name)||[],_=u.filter(e=>g.includes(e));_?.length>0&&e.warn(`custom-fields: trying to update disabled values: ${_.join(`, `)}`);let v=u.map(e=>{let t=m.find(t=>t.name===e),n=i[t.fieldType],r=n?n(c[e]):c[e];return{modelId:o,updatedAt:new Date,customFieldDefinitionId:t.id,value:r===void 0?t.defaultValue:r}});return Promise.all(v.map(async e=>{let[t]=await r.upsert(e,{transaction:l.transaction});return t}))};export{a as findValuesByModelIds,o as updateValues};
|
|
2
|
-
//# sourceMappingURL=value.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"value.js","names":["CustomFieldValue","where: WhereOptions","DefinitionRepo.findAll","values: CreateCustomFieldValue[]"],"sources":["../../src/repository/value.ts"],"sourcesContent":["import type { FindOptions, Transactionable, WhereOptions } from 'sequelize';\nimport { CustomFieldValue, CustomFieldDefinition } from '../models';\nimport * as DefinitionRepo from './definition';\nimport type { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';\nimport logger from '../utils/logger';\nimport { MissingDefinitionError } from '../errors';\nimport type { ModelOptions } from '../types';\nimport { formatFunctions } from './utils/formatValues';\n\nexport const findByModelIdAndDefinition = async (modelId: string, customFieldDefinitionId: string): Promise<CustomFieldValue[]> =>\n CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [CustomFieldDefinition] });\n\nexport const create = async (data: CreateCustomFieldValue, withAssociations = false): Promise<CustomFieldValue> => {\n const created = await CustomFieldValue.create(data);\n if (withAssociations) {\n const createdWithAssociations = await findByModelIdAndDefinition(created.modelId, created.customFieldDefinitionId);\n return createdWithAssociations?.[0];\n }\n return created;\n};\n\nexport const findAllValues = async (): Promise<CustomFieldValue[]> => CustomFieldValue.findAll({ include: [CustomFieldDefinition] });\n/**\n * Get all values for model instance id (with their definitions)\n * @param modelId\n * @returns CustomFieldValue[]\n */\nexport const findValuesByModelId = async (modelId: string): Promise<CustomFieldValue[]> => CustomFieldValue.findAll({ where: { modelId }, include: [CustomFieldDefinition] });\n\n/**\n* Retrieves custom field values for given model IDs\n* @param modelIds - An array of model IDs to query custom field values for.\n* @param options - Optional configuration object.\n*/\nexport const findValuesByModelIds = async (modelIds: string[], options?: Transactionable): Promise<CustomFieldValue[]> => {\n const { transaction } = options;\n return CustomFieldValue.findAll({\n where: { modelId: modelIds },\n transaction,\n raw: true,\n nest: true,\n });\n};\n\n/**\n * Try to update custom field values for a model instance.\n * Create new value record if not exists, but fails if value's definition not exist.\n * Return the updated values\n */\nexport const updateValues = async (\n modelType: string,\n modelId: string,\n identifiers: string[],\n valuesToUpdate: ValuesToUpdate,\n options: FindOptions & { modelOptions?: ModelOptions } = {},\n): Promise<CustomFieldValue[]> => {\n const names = Object.keys(valuesToUpdate);\n logger.debug(`custom-fields: updating values for ${modelType} ${modelId}`, {\n names,\n optionsKeys: options ? Object.keys(options) : null,\n valuesToUpdate,\n identifiers,\n });\n const { modelOptions, transaction } = options;\n\n const where: WhereOptions = {\n modelType,\n name: names,\n ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions.include?.(identifiers) }) ?? [];\n\n const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);\n if (fieldDefinitions.length !== names.length) {\n logger.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });\n const missingDefinitions = names.filter((name) => !fieldDefinitions.some((def) => def.name === name));\n throw new MissingDefinitionError(missingDefinitions);\n }\n\n const disabledNames = disabledDefinitions?.map((def) => def.name) || [];\n const valuesWithDisabledDefinitions = names.filter((name) => disabledNames.includes(name));\n if (valuesWithDisabledDefinitions?.length > 0) {\n logger.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);\n }\n\n const values: CreateCustomFieldValue[] = names.map((name) => {\n const fieldDefinition = fieldDefinitions.find((def) => def.name === name);\n const formatFunction = formatFunctions[fieldDefinition.fieldType];\n const value = formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name];\n return {\n modelId,\n updatedAt: new Date(),\n customFieldDefinitionId: fieldDefinition.id,\n value: value !== undefined ? value : fieldDefinition.defaultValue,\n };\n });\n\n return Promise.all(values.map(async (value) => {\n const [cfv] = await CustomFieldValue.upsert(value, {\n transaction: options.transaction,\n });\n return cfv;\n }));\n};\n\nexport const deleteValue = (\n id: string,\n options: any = {},\n): Promise<any> => CustomFieldValue.update(\n { deletedAt: new Date() },\n {\n where: { id },\n transaction: options.transaction,\n },\n);\n"],"mappings":"gRAkCA,MAAa,EAAuB,MAAO,EAAoB,IAA2D,CACxH,GAAM,CAAE,eAAgB,EACxB,OAAOA,EAA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gB,GACzC,MAAO,IAAU,IAAA,GAAoB,EAAgB,aAAxB,EAC9B,EACD,CAEF,OAAO,QAAQ,IAAI,EAAO,IAAI,KAAO,IAAU,CAC7C,GAAM,CAAC,GAAO,MAAMH,EAAiB,OAAO,EAAO,CACjD,YAAa,EAAQ,YACtB,CAAC,CACF,OAAO,GACP,CAAC"}
|
package/dist/scopes/filter.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/helpers/index.cjs`),n=require(`./helpers/filter.helpers.cjs`);let r=require(`sequelize`);r=e.__toESM(r);let i=require(`sequelize-typescript`);i=e.__toESM(i);let a=require(`@autofleet/common-types`);a=e.__toESM(a);const o=(e,t)=>({replacementsMap:a,scopeValue:o})=>{if(!o||Object.keys(o).length===0)return{};let s=t?.useCustomFieldsEntries?n.SubQueryType.ENTRIES:n.SubQueryType.VALUES,c=new Map(Object.entries(a).map(([e,t])=>[t,e])),l=Object.entries(o).map(([e,t])=>{switch(s){case n.SubQueryType.ENTRIES:return n.formatConditionsForEntries(e,t,c);case n.SubQueryType.VALUES:return n.formatConditionsForValues(e,t,c);default:return!1}}).filter(Boolean);if(l.length===0)return{};let u=n.getFilterCustomFieldsSubQuery(s,e,l);return{where:{id:{[r.Op.in]:i.Sequelize.literal(`(${u})`)}},replacements:a}},s=a.customFields.CUSTOM_FIELDS_FILTER_SCOPE,c=(e,r)=>({replacementsMap:a,scopeValue:o})=>{if(!o||o.length===0)return{};let s=r?.useCustomFieldsEntries?n.SubQueryType.ENTRIES:n.SubQueryType.VALUES,c=t.generateRandomString(),l=Object.entries(o).map(([t])=>{let r=Object.keys(a).find(e=>a[e]===t);return[i.Sequelize.literal(n.getSortCustomFieldsSubQuery(s,e,r)),c]}),u=Object.entries(o).map(([,e])=>{let t=typeof e==`string`?e:Object.values(e)[0];return i.Sequelize.literal(`"${c}" ${t||`ASC`}`)});return{attributes:{include:l},order:u,replacements:a}};exports.customFieldsFilterScope=o,exports.customFieldsSortScope=c;
|
|
2
|
-
//# sourceMappingURL=filter.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"filter.cjs","names":["SubQueryType","formatConditionsForEntries","formatConditionsForValues","getFilterCustomFieldsSubQuery","Op","Sequelize","scopeName: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE","customFields","generateRandomString","getSortCustomFieldsSubQuery"],"sources":["../../src/scopes/filter.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { Op } from 'sequelize';\nimport type { Literal } from 'sequelize/types/utils';\nimport { Sequelize } from 'sequelize-typescript';\nimport { customFields } from '@autofleet/common-types';\nimport { generateRandomString } from '../utils/helpers';\nimport type { CustomFieldOptions } from '../types';\nimport {\n formatConditionsForEntries,\n formatConditionsForValues,\n getFilterCustomFieldsSubQuery,\n getSortCustomFieldsSubQuery,\n SubQueryType,\n type ConditionValue,\n type CustomFieldFilterOptions,\n} from './helpers/filter.helpers';\n\ntype customFieldsFilterScopeParams = {\n replacementsMap: Record<string, string>;\n scopeValue: Record<string, ConditionValue>;\n}\n\n/**\n * A Sequelize scope for filtering models by custom fields.\n * This scope builds a WHERE clause to be applied on the main query.\n *\n * @param name - The model type name used to join custom_field_definitions.\n * @returns A function that takes conditions and returns the Sequelize options object.\n */\nexport const customFieldsFilterScope = (\n name: string,\n options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n) => ({ replacementsMap: replacements, scopeValue: conditions }: customFieldsFilterScopeParams): CustomFieldFilterOptions => {\n if (!conditions || Object.keys(conditions).length === 0) {\n return {};\n }\n\n const queryType = options?.useCustomFieldsEntries ? SubQueryType.ENTRIES : SubQueryType.VALUES;\n const reverseReplacementsMap = new Map(Object.entries(replacements).map(([key, value]) => [value, key]));\n // Build the WHERE clause for custom field filtering\n const conditionsStrings = Object.entries(conditions).map(([key, condition]) => {\n switch (queryType) {\n case SubQueryType.ENTRIES:\n return formatConditionsForEntries(key, condition, reverseReplacementsMap);\n case SubQueryType.VALUES:\n return formatConditionsForValues(key, condition, reverseReplacementsMap);\n default:\n return false;\n }\n }).filter(Boolean);\n if (conditionsStrings.length === 0) {\n return {};\n }\n const subQuery = getFilterCustomFieldsSubQuery(queryType, name, conditionsStrings);\n\n return {\n where: {\n id: {\n [Op.in]: Sequelize.literal(`(${subQuery})`),\n },\n },\n replacements,\n };\n};\n\nexport const scopeName: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport const customFieldsSortScope = (\n name: string,\n options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n) => ({ replacementsMap, scopeValue: sort }: { replacementsMap: Record<string, string>; scopeValue: Record<string, ConditionValue>; }): {\n attributes: { include: (string | Literal)[][]; };\n order: Literal[];\n replacements: Record<string, string>;\n} | Record<string, never> => {\n if (!sort || (sort as unknown as any[]).length === 0) {\n return {};\n }\n\n const queryType = options?.useCustomFieldsEntries ? SubQueryType.ENTRIES : SubQueryType.VALUES;\n const randomStr = generateRandomString();\n const includes = Object.entries(sort).map(([key]) => {\n const replacementKey = Object.keys(replacementsMap).find(\n (randomString) => replacementsMap[randomString] === key,\n );\n return ([\n Sequelize.literal(getSortCustomFieldsSubQuery(queryType, name, replacementKey)),\n randomStr,\n ]);\n });\n\n const orders = Object.entries(sort).map(([, sortObject]) => {\n const direction = typeof sortObject === 'string' ? sortObject : Object.values(sortObject)[0];\n return Sequelize.literal(`\"${randomStr}\" ${direction || 'ASC'}`);\n });\n return {\n attributes: {\n include: includes,\n },\n order: orders,\n replacements: replacementsMap,\n };\n};\n"],"mappings":"6RA6BA,MAAa,GACX,EACA,KACI,CAAE,gBAAiB,EAAc,WAAY,KAA0E,CAC3H,GAAI,CAAC,GAAc,OAAO,KAAK,EAAW,CAAC,SAAW,EACpD,MAAO,EAAE,CAGX,IAAM,EAAY,GAAS,uBAAyBA,EAAAA,aAAa,QAAUA,EAAAA,aAAa,OAClF,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GAAa,QAAQ,EAChE,CACF,MAAO,CACL,WAAY,CACV,QAAS,EACV,CACD,MAAO,EACP,aAAc,EACf"}
|
package/dist/scopes/filter.d.cts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { CustomFieldOptions } from "../types/index.cjs";
|
|
2
|
-
import { ConditionValue } from "./helpers/filter.helpers.cjs";
|
|
3
|
-
import { customFields } from "@autofleet/common-types";
|
|
4
|
-
import { Literal } from "sequelize/types/utils";
|
|
5
|
-
|
|
6
|
-
//#region src/scopes/filter.d.ts
|
|
7
|
-
|
|
8
|
-
declare const customFieldsSortScope: (name: string, options?: Pick<CustomFieldOptions, "useCustomFieldsEntries">) => ({
|
|
9
|
-
replacementsMap,
|
|
10
|
-
scopeValue: sort
|
|
11
|
-
}: {
|
|
12
|
-
replacementsMap: Record<string, string>;
|
|
13
|
-
scopeValue: Record<string, ConditionValue>;
|
|
14
|
-
}) => {
|
|
15
|
-
attributes: {
|
|
16
|
-
include: (string | Literal)[][];
|
|
17
|
-
};
|
|
18
|
-
order: Literal[];
|
|
19
|
-
replacements: Record<string, string>;
|
|
20
|
-
} | Record<string, never>;
|
|
21
|
-
//#endregion
|
|
22
|
-
export { customFieldsSortScope };
|
|
23
|
-
//# sourceMappingURL=filter.d.cts.map
|
package/dist/scopes/filter.d.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { CustomFieldOptions } from "../types/index.js";
|
|
2
|
-
import { ConditionValue } from "./helpers/filter.helpers.js";
|
|
3
|
-
import { customFields } from "@autofleet/common-types";
|
|
4
|
-
import { Literal } from "sequelize/types/utils";
|
|
5
|
-
|
|
6
|
-
//#region src/scopes/filter.d.ts
|
|
7
|
-
|
|
8
|
-
declare const customFieldsSortScope: (name: string, options?: Pick<CustomFieldOptions, "useCustomFieldsEntries">) => ({
|
|
9
|
-
replacementsMap,
|
|
10
|
-
scopeValue: sort
|
|
11
|
-
}: {
|
|
12
|
-
replacementsMap: Record<string, string>;
|
|
13
|
-
scopeValue: Record<string, ConditionValue>;
|
|
14
|
-
}) => {
|
|
15
|
-
attributes: {
|
|
16
|
-
include: (string | Literal)[][];
|
|
17
|
-
};
|
|
18
|
-
order: Literal[];
|
|
19
|
-
replacements: Record<string, string>;
|
|
20
|
-
} | Record<string, never>;
|
|
21
|
-
//#endregion
|
|
22
|
-
export { customFieldsSortScope };
|
|
23
|
-
//# sourceMappingURL=filter.d.ts.map
|
package/dist/scopes/filter.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{generateRandomString as e}from"../utils/helpers/index.js";import{SubQueryType as t,formatConditionsForEntries as n,formatConditionsForValues as r,getFilterCustomFieldsSubQuery as i,getSortCustomFieldsSubQuery as a}from"./helpers/filter.helpers.js";import{Op as o}from"sequelize";import{Sequelize as s}from"sequelize-typescript";import{customFields as c}from"@autofleet/common-types";const l=(e,a)=>({replacementsMap:c,scopeValue:l})=>{if(!l||Object.keys(l).length===0)return{};let u=a?.useCustomFieldsEntries?t.ENTRIES:t.VALUES,d=new Map(Object.entries(c).map(([e,t])=>[t,e])),f=Object.entries(l).map(([e,i])=>{switch(u){case t.ENTRIES:return n(e,i,d);case t.VALUES:return r(e,i,d);default:return!1}}).filter(Boolean);if(f.length===0)return{};let p=i(u,e,f);return{where:{id:{[o.in]:s.literal(`(${p})`)}},replacements:c}};c.CUSTOM_FIELDS_FILTER_SCOPE;const u=(n,r)=>({replacementsMap:i,scopeValue:o})=>{if(!o||o.length===0)return{};let c=r?.useCustomFieldsEntries?t.ENTRIES:t.VALUES,l=e(),u=Object.entries(o).map(([e])=>{let t=Object.keys(i).find(t=>i[t]===e);return[s.literal(a(c,n,t)),l]}),d=Object.entries(o).map(([,e])=>{let t=typeof e==`string`?e:Object.values(e)[0];return s.literal(`"${l}" ${t||`ASC`}`)});return{attributes:{include:u},order:d,replacements:i}};export{l as customFieldsFilterScope,u as customFieldsSortScope};
|
|
2
|
-
//# sourceMappingURL=filter.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"filter.js","names":["scopeName: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE"],"sources":["../../src/scopes/filter.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { Op } from 'sequelize';\nimport type { Literal } from 'sequelize/types/utils';\nimport { Sequelize } from 'sequelize-typescript';\nimport { customFields } from '@autofleet/common-types';\nimport { generateRandomString } from '../utils/helpers';\nimport type { CustomFieldOptions } from '../types';\nimport {\n formatConditionsForEntries,\n formatConditionsForValues,\n getFilterCustomFieldsSubQuery,\n getSortCustomFieldsSubQuery,\n SubQueryType,\n type ConditionValue,\n type CustomFieldFilterOptions,\n} from './helpers/filter.helpers';\n\ntype customFieldsFilterScopeParams = {\n replacementsMap: Record<string, string>;\n scopeValue: Record<string, ConditionValue>;\n}\n\n/**\n * A Sequelize scope for filtering models by custom fields.\n * This scope builds a WHERE clause to be applied on the main query.\n *\n * @param name - The model type name used to join custom_field_definitions.\n * @returns A function that takes conditions and returns the Sequelize options object.\n */\nexport const customFieldsFilterScope = (\n name: string,\n options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n) => ({ replacementsMap: replacements, scopeValue: conditions }: customFieldsFilterScopeParams): CustomFieldFilterOptions => {\n if (!conditions || Object.keys(conditions).length === 0) {\n return {};\n }\n\n const queryType = options?.useCustomFieldsEntries ? SubQueryType.ENTRIES : SubQueryType.VALUES;\n const reverseReplacementsMap = new Map(Object.entries(replacements).map(([key, value]) => [value, key]));\n // Build the WHERE clause for custom field filtering\n const conditionsStrings = Object.entries(conditions).map(([key, condition]) => {\n switch (queryType) {\n case SubQueryType.ENTRIES:\n return formatConditionsForEntries(key, condition, reverseReplacementsMap);\n case SubQueryType.VALUES:\n return formatConditionsForValues(key, condition, reverseReplacementsMap);\n default:\n return false;\n }\n }).filter(Boolean);\n if (conditionsStrings.length === 0) {\n return {};\n }\n const subQuery = getFilterCustomFieldsSubQuery(queryType, name, conditionsStrings);\n\n return {\n where: {\n id: {\n [Op.in]: Sequelize.literal(`(${subQuery})`),\n },\n },\n replacements,\n };\n};\n\nexport const scopeName: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport const customFieldsSortScope = (\n name: string,\n options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n) => ({ replacementsMap, scopeValue: sort }: { replacementsMap: Record<string, string>; scopeValue: Record<string, ConditionValue>; }): {\n attributes: { include: (string | Literal)[][]; };\n order: Literal[];\n replacements: Record<string, string>;\n} | Record<string, never> => {\n if (!sort || (sort as unknown as any[]).length === 0) {\n return {};\n }\n\n const queryType = options?.useCustomFieldsEntries ? SubQueryType.ENTRIES : SubQueryType.VALUES;\n const randomStr = generateRandomString();\n const includes = Object.entries(sort).map(([key]) => {\n const replacementKey = Object.keys(replacementsMap).find(\n (randomString) => replacementsMap[randomString] === key,\n );\n return ([\n Sequelize.literal(getSortCustomFieldsSubQuery(queryType, name, replacementKey)),\n randomStr,\n ]);\n });\n\n const orders = Object.entries(sort).map(([, sortObject]) => {\n const direction = typeof sortObject === 'string' ? sortObject : Object.values(sortObject)[0];\n return Sequelize.literal(`\"${randomStr}\" ${direction || 'ASC'}`);\n });\n return {\n attributes: {\n include: includes,\n },\n order: orders,\n replacements: replacementsMap,\n };\n};\n"],"mappings":"sYA6BA,MAAa,GACX,EACA,KACI,CAAE,gBAAiB,EAAc,WAAY,KAA0E,CAC3H,GAAI,CAAC,GAAc,OAAO,KAAK,EAAW,CAAC,SAAW,EACpD,MAAO,EAAE,CAGX,IAAM,EAAY,GAAS,uBAAyB,EAAa,QAAU,EAAa,OAClF,EAAyB,IAAI,IAAI,OAAO,QAAQ,EAAa,CAAC,KAAK,CAAC,EAAK,KAAW,CAAC,EAAO,EAAI,CAAC,CAAC,CAElG,EAAoB,OAAO,QAAQ,EAAW,CAAC,KAAK,CAAC,EAAK,KAAe,CAC7E,OAAQ,EAAR,CACE,KAAK,EAAa,QAChB,OAAO,EAA2B,EAAK,EAAW,EAAuB,CAC3E,KAAK,EAAa,OAChB,OAAO,EAA0B,EAAK,EAAW,EAAuB,CAC1E,QACE,MAAO,KAEX,CAAC,OAAO,QAAQ,CAClB,GAAI,EAAkB,SAAW,EAC/B,MAAO,EAAE,CAEX,IAAM,EAAW,EAA8B,EAAW,EAAM,EAAkB,CAElF,MAAO,CACL,MAAO,CACL,GAAI,EACD,EAAG,IAAK,EAAU,QAAQ,IAAI,EAAS,GAAG,CAC5C,CACF,CACD,eACD,EAGsE,EAAa,2BAEtF,MAAa,GACX,EACA,KACI,CAAE,kBAAiB,WAAY,KAIR,CAC3B,GAAI,CAAC,GAAS,EAA0B,SAAW,EACjD,MAAO,EAAE,CAGX,IAAM,EAAY,GAAS,uBAAyB,EAAa,QAAU,EAAa,OAClF,EAAY,GAAsB,CAClC,EAAW,OAAO,QAAQ,EAAK,CAAC,KAAK,CAAC,KAAS,CACnD,IAAM,EAAiB,OAAO,KAAK,EAAgB,CAAC,KACjD,GAAiB,EAAgB,KAAkB,EACrD,CACD,MAAQ,CACN,EAAU,QAAQ,EAA4B,EAAW,EAAM,EAAe,CAAC,CAC/E,EACD,EACD,CAEI,EAAS,OAAO,QAAQ,EAAK,CAAC,KAAK,EAAG,KAAgB,CAC1D,IAAM,EAAY,OAAO,GAAe,SAAW,EAAa,OAAO,OAAO,EAAW,CAAC,GAC1F,OAAO,EAAU,QAAQ,IAAI,EAAU,IAAI,GAAa,QAAQ,EAChE,CACF,MAAO,CACL,WAAY,CACV,QAAS,EACV,CACD,MAAO,EACP,aAAc,EACf"}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
let e=function(e){return e.VALUES=`values`,e.ENTRIES=`entries`,e}({});const t=e=>Array.isArray(e)&&typeof e[0]==`string`,n=e=>[`true`,`false`].includes(e.toString()),r=e=>e instanceof Date||Object.prototype.toString.call(e)===`[object Date]`,i=(e,t)=>`to_jsonb(${e}::${t})`,a=e=>i(e,`text`),o=e=>i(e,`boolean`),s=e=>i(e,`numeric`),c=(e,t)=>r(t)?i(e,`timestamp`):e,l=` AND `,u=` OR `,d=`cd`,f=`cd.name`,p=`cv`,m=`cv.value`,h=`ce`,g=(e,t,i,a)=>{let o=`text`;r(e)?o=`date`:Number.isNaN(Number(e))?n(e)&&(o=`boolean`):o=`numeric`;let s=a.get(e);return`(jsonb_extract_path_text(ce.custom_fields, :${i})::${o}) ${t} :${s}`},_=e=>{let t=e;return n(e)?t=e===`true`:Number.isNaN(Number(e))||(t=Number(e)),t},v=(e,t)=>{let r=_(e),i=JSON.stringify({[t]:r}),a;return n(e)&&(a=`ce.custom_fields @> '${JSON.stringify({[t]:e})}'`),`
|
|
2
|
-
(
|
|
3
|
-
${a?`${a} OR`:``}
|
|
4
|
-
ce.custom_fields @> '${i}'
|
|
5
|
-
)
|
|
6
|
-
`},y=(t,n,r)=>{switch(t){case e.VALUES:return`
|
|
7
|
-
SELECT cv.model_id
|
|
8
|
-
FROM custom_field_values AS cv
|
|
9
|
-
INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id
|
|
10
|
-
${l}cd.model_type = '${n}'
|
|
11
|
-
WHERE ${r.join(u)}
|
|
12
|
-
${l}cv.deleted_at IS NULL${l}cd.deleted_at IS NULL
|
|
13
|
-
GROUP BY cv.model_id
|
|
14
|
-
HAVING COUNT(DISTINCT cv.custom_field_definition_id) = ${r.length}
|
|
15
|
-
`.replace(/\n/g,``);case e.ENTRIES:return`
|
|
16
|
-
SELECT ce.model_id
|
|
17
|
-
FROM custom_field_entries ce
|
|
18
|
-
JOIN custom_field_definitions cfd
|
|
19
|
-
ON ce.model_type = cfd.model_type
|
|
20
|
-
AND ce.entity_id = cfd.entity_id
|
|
21
|
-
WHERE
|
|
22
|
-
cfd.deleted_at IS NULL AND
|
|
23
|
-
${r.join(l)}
|
|
24
|
-
`;default:throw Error(`Invalid query type`)}},b=(t,n,r)=>{switch(t){case e.VALUES:return`(
|
|
25
|
-
SELECT value
|
|
26
|
-
FROM (SELECT cv.model_id, cv.value
|
|
27
|
-
FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd
|
|
28
|
-
ON cv.custom_field_definition_id = cd.id
|
|
29
|
-
${l}cd.model_type = '${n}'
|
|
30
|
-
WHERE cv.model_id = "${n}"."id"
|
|
31
|
-
${l}cd.name = :${r}
|
|
32
|
-
) AS CustomFieldAggregation
|
|
33
|
-
)
|
|
34
|
-
`;case e.ENTRIES:return`(
|
|
35
|
-
SELECT
|
|
36
|
-
customFields.value
|
|
37
|
-
FROM
|
|
38
|
-
custom_field_entries AS ce,
|
|
39
|
-
jsonb_each_text(custom_fields) AS customFields
|
|
40
|
-
WHERE
|
|
41
|
-
customFields.key = :${r}${l}
|
|
42
|
-
ce.model_type = '${n}'${l}
|
|
43
|
-
ce.model_id = "${n}"."id"
|
|
44
|
-
)
|
|
45
|
-
`;default:throw Error(`Invalid query type`)}},x=(e,r,i)=>{let d=i.get(e);if(!d)return!1;let f=`(cd.name = :${d})`;if(Array.isArray(r)){if(r.length===0)return!1;if(t(r)){let e=r.flatMap(e=>{let t=i.get(e);return n(e)?[a(`:${t}`),o(`:${t}`)]:Number.isNaN(Number(e))?a(`:${t}`):s(`:${t}`)}).join(`,`);return`(${f}${l}${m} IN (${e}))`}return r.map(e=>{let t=i.get(e.value),n=a(`:${t}`);return`(${f}${l}${c(m,e.value)} ${e.operator} ${n})`}).join(l)}if(typeof r==`string`||typeof r==`number`){let e=i.get(r),t=Number.isNaN(Number(r))?a(`:${e}`):s(`:${e}`),d=n(r)?`${u}${m} = ${o(`:${e}`)}`:``;return`(${f}${l}(${c(m,r)} = ${t}${d}))`}if(r?.operator){let e=i.get(r.value),t=a(`:${e}`);return`( ${f}${l}${c(m,r.value)} ${r.operator} ${t})`}return!1},S=(e,n,r)=>{let i=r.get(e);return i?Array.isArray(n)?n.length===0?!1:t(n)?`( ${n.map(t=>v(t,e)).join(`${u}\n`)})`:n.map(e=>g(e.value,e.operator,i,r)).join(l):typeof n==`string`||typeof n==`number`?v(n,e):n?.operator?g(n.value,n.operator,i,r):!1:!1};exports.SubQueryType=e,exports.formatConditionsForEntries=S,exports.formatConditionsForValues=x,exports.getFilterCustomFieldsSubQuery=y,exports.getSortCustomFieldsSubQuery=b;
|
|
46
|
-
//# sourceMappingURL=filter.helpers.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"filter.helpers.cjs","names":["CD_NAME_COLUMN: `${typeof CD_TABLE_ALIAS}.name`","CV_VALUE_COLUMN: `${typeof CV_TABLE_ALIAS}.value`","formattedValue: string | number | boolean"],"sources":["../../../src/scopes/helpers/filter.helpers.ts"],"sourcesContent":["import type { WhereOptions } from 'sequelize';\n\n/**\n * Type representing possible condition values.\n * Currently supporting strings and arrays of strings.\n * More types to be added (TBA).\n */\nexport type ConditionWithOperator = {\n operator: string;\n value: string;\n};\nexport type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];\n\nexport type CustomFieldSort = {\n field: string;\n direction: 'ASC' | 'DESC';\n}\n\nexport type CustomFieldFilterOptions = {\n where?: WhereOptions;\n replacements?: Record<string, string>;\n}\n\nexport enum SubQueryType {\n VALUES = 'values',\n ENTRIES = 'entries',\n}\n\nexport const isConditionStringArray = (input: any): input is string[] => Array.isArray(input) && typeof input[0] === 'string';\nexport const isBooleanString = (input: string): boolean => ['true', 'false'].includes(input.toString());\nexport const isDate = (input: any): input is Date => input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';\n\nexport const castValueToJsonb = (value: string, type: string) => `to_jsonb(${value}::${type})`;\nexport const castValueToJsonbText = (value: string): string => castValueToJsonb(value, 'text');\nexport const castValueToJsonbBoolean = (value: string): string => castValueToJsonb(value, 'boolean');\nexport const castValueToJsonbNumeric = (value: string): string => castValueToJsonb(value, 'numeric');\nexport const castIfNeeded = (columnName: string, conditionValue: string): string => {\n if (isDate(conditionValue)) {\n return castValueToJsonb(columnName, 'timestamp');\n }\n return columnName;\n};\n\nexport const AND_DELIMITER = ' AND ';\nexport const OR_DELIMITER = ' OR ';\nexport const CD_TABLE_ALIAS = 'cd';\nexport const CD_NAME_COLUMN: `${typeof CD_TABLE_ALIAS}.name` = `${CD_TABLE_ALIAS}.name`;\nexport const CV_TABLE_ALIAS = 'cv';\nexport const CV_VALUE_COLUMN: `${typeof CV_TABLE_ALIAS}.value` = `${CV_TABLE_ALIAS}.value`;\nexport const CE_TABLE_ALIAS = 'ce';\n\nconst getSingleConditionWithOperator = (value: any, operator: string, replacementKey: string, reverseReplacementsMap: Map<string, string>) => {\n let type = 'text';\n if (isDate(value)) {\n type = 'date';\n } else if (!Number.isNaN(Number(value))) {\n type = 'numeric';\n } else if (isBooleanString(value)) {\n type = 'boolean';\n }\n const replacedValue = reverseReplacementsMap.get(value);\n\n return `(jsonb_extract_path_text(${CE_TABLE_ALIAS}.custom_fields, :${replacementKey})::${type}) ${operator} :${replacedValue}`;\n};\n\nconst getFormattedValue = (value: string) => {\n let formattedValue: string | number | boolean = value;\n if (isBooleanString(value)) {\n formattedValue = value === 'true';\n } else if (!Number.isNaN(Number(value))) {\n formattedValue = Number(value);\n }\n\n return formattedValue;\n};\n\nconst getJSONSubQuery = (value: string, key: string) => {\n const formattedValue = getFormattedValue(value);\n const jsonQuery = JSON.stringify({ [key]: formattedValue });\n let jsonQueryWithStringBoolean;\n if (isBooleanString(value)) {\n jsonQueryWithStringBoolean = `${CE_TABLE_ALIAS}.custom_fields @> '${JSON.stringify({ [key]: value })}'`;\n }\n return `\n (\n ${jsonQueryWithStringBoolean ? `${jsonQueryWithStringBoolean} OR` : ''}\n ${CE_TABLE_ALIAS}.custom_fields @> '${jsonQuery}'\n )\n `;\n};\n\nexport const getFilterCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, conditionsStrings: Array<string | boolean>): string => {\n switch (queryType) {\n case SubQueryType.VALUES:\n return `\n SELECT ${CV_TABLE_ALIAS}.model_id\n FROM custom_field_values AS ${CV_TABLE_ALIAS}\n INNER JOIN custom_field_definitions AS ${CD_TABLE_ALIAS} ON ${CV_TABLE_ALIAS}.custom_field_definition_id = ${CD_TABLE_ALIAS}.id\n ${AND_DELIMITER}${CD_TABLE_ALIAS}.model_type = '${modelType}'\n WHERE ${conditionsStrings.join(OR_DELIMITER)}\n ${AND_DELIMITER}${CV_TABLE_ALIAS}.deleted_at IS NULL${AND_DELIMITER}${CD_TABLE_ALIAS}.deleted_at IS NULL\n GROUP BY ${CV_TABLE_ALIAS}.model_id\n HAVING COUNT(DISTINCT ${CV_TABLE_ALIAS}.custom_field_definition_id) = ${conditionsStrings.length}\n `.replace(/\\n/g, '');\n case SubQueryType.ENTRIES:\n return `\n SELECT ce.model_id\n FROM custom_field_entries ce\n JOIN custom_field_definitions cfd\n ON ce.model_type = cfd.model_type\n AND ce.entity_id = cfd.entity_id\n WHERE\n cfd.deleted_at IS NULL AND\n ${conditionsStrings.join(AND_DELIMITER)}\n `;\n default:\n throw new Error('Invalid query type');\n }\n};\n\nexport const getSortCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, replacementKey: string): string => {\n switch (queryType) {\n case SubQueryType.VALUES:\n return `(\n SELECT value\n FROM (SELECT cv.model_id, cv.value\n FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd\n ON cv.custom_field_definition_id = cd.id\n ${AND_DELIMITER}cd.model_type = '${modelType}'\n WHERE cv.model_id = \"${modelType}\".\"id\"\n ${AND_DELIMITER}cd.name = :${replacementKey}\n ) AS CustomFieldAggregation\n )\n `;\n case SubQueryType.ENTRIES:\n return `(\n SELECT\n customFields.value\n FROM\n custom_field_entries AS ${CE_TABLE_ALIAS},\n jsonb_each_text(custom_fields) AS customFields\n WHERE\n customFields.key = :${replacementKey}${AND_DELIMITER}\n ${CE_TABLE_ALIAS}.model_type = '${modelType}'${AND_DELIMITER}\n ${CE_TABLE_ALIAS}.model_id = \"${modelType}\".\"id\"\n )\n `;\n default:\n throw new Error('Invalid query type');\n }\n};\n\nexport const formatConditionsForValues = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>): false | string => {\n const replacementKey = reverseReplacementsMap.get(key);\n if (!replacementKey) {\n return false;\n }\n\n const columnCondition = `(${CD_NAME_COLUMN} = :${replacementKey})`;\n if (Array.isArray(condition)) {\n if (condition.length === 0) {\n // if empty array, the condition is ignored\n return false;\n }\n\n if (isConditionStringArray(condition)) {\n const values = condition.flatMap((v) => {\n const valRandom = reverseReplacementsMap.get(v);\n if (isBooleanString(v)) {\n return [castValueToJsonbText(`:${valRandom}`), castValueToJsonbBoolean(`:${valRandom}`)];\n }\n if (!Number.isNaN(Number(v))) {\n return castValueToJsonbNumeric(`:${valRandom}`);\n }\n return castValueToJsonbText(`:${valRandom}`);\n }).join(',');\n return `(${columnCondition}${AND_DELIMITER}${CV_VALUE_COLUMN} IN (${values}))`;\n }\n return condition.map((c) => {\n const valRep = reverseReplacementsMap.get(c.value);\n const valueAsJsonb = castValueToJsonbText(`:${valRep}`);\n\n return `(${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, c.value)} ${c.operator} ${valueAsJsonb})`;\n }).join(AND_DELIMITER);\n }\n if (typeof condition === 'string' || typeof condition === 'number') {\n const conditionRep = reverseReplacementsMap.get(condition);\n const valueAsJsonb = !Number.isNaN(Number(condition)) ? castValueToJsonbNumeric(`:${conditionRep}`) : castValueToJsonbText(`:${conditionRep}`);\n const valueAsJsonbBoolean = isBooleanString(condition) ? `${OR_DELIMITER}${CV_VALUE_COLUMN} = ${castValueToJsonbBoolean(`:${conditionRep}`)}` : '';\n return `(${columnCondition}${AND_DELIMITER}(${castIfNeeded(CV_VALUE_COLUMN, condition)} = ${valueAsJsonb}${valueAsJsonbBoolean}))`;\n }\n if (condition?.operator) {\n const valueRep = reverseReplacementsMap.get(condition.value);\n const valueAsJsonb = castValueToJsonbText(`:${valueRep}`);\n return `( ${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, condition.value)} ${condition.operator} ${valueAsJsonb})`;\n }\n return false;\n};\n\nexport const formatConditionsForEntries = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>): false | string => {\n const replacementKey = reverseReplacementsMap.get(key);\n if (!replacementKey) {\n return false;\n }\n\n if (Array.isArray(condition)) {\n if (condition.length === 0) {\n // if empty array, the condition is ignored\n return false;\n }\n\n if (isConditionStringArray(condition)) {\n const values = condition.map((value) => getJSONSubQuery(value, key)).join(`${OR_DELIMITER}\\n`);\n return `( ${values})`;\n }\n return condition.map((c) => getSingleConditionWithOperator(c.value, c.operator, replacementKey, reverseReplacementsMap)).join(AND_DELIMITER);\n }\n\n if (typeof condition === 'string' || typeof condition === 'number') {\n return getJSONSubQuery(condition, key);\n }\n\n if (condition?.operator) {\n return getSingleConditionWithOperator(condition.value, condition.operator, replacementKey, reverseReplacementsMap);\n }\n return false;\n};\n"],"mappings":"AAuBA,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,iBAGF,MAAa,EAA0B,GAAkC,MAAM,QAAQ,EAAM,EAAI,OAAO,EAAM,IAAO,SACxG,EAAmB,GAA2B,CAAC,OAAQ,QAAQ,CAAC,SAAS,EAAM,UAAU,CAAC,CAC1F,EAAU,GAA8B,aAAiB,MAAQ,OAAO,UAAU,SAAS,KAAK,EAAM,GAAK,gBAE3G,GAAoB,EAAe,IAAiB,YAAY,EAAM,IAAI,EAAK,GAC/E,EAAwB,GAA0B,EAAiB,EAAO,OAAO,CACjF,EAA2B,GAA0B,EAAiB,EAAO,UAAU,CACvF,EAA2B,GAA0B,EAAiB,EAAO,UAAU,CACvF,GAAgB,EAAoB,IAC3C,EAAO,EAAe,CACjB,EAAiB,EAAY,YAAY,CAE3C,EAGI,EAAgB,QAChB,EAAe,OACf,EAAiB,KACjBA,EAAkD,UAClD,EAAiB,KACjBC,EAAoD,WACpD,EAAiB,KAExB,GAAkC,EAAY,EAAkB,EAAwB,IAAgD,CAC5I,IAAI,EAAO,OACP,EAAO,EAAM,CACf,EAA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AAkB,IAAgB,EAAa,EAAiB,EAAU,MAAM,CAAC,GAAG,EAAU,SAAS,GAAG,EAAa,GAErI,MAAO,IAGI,GAA8B,EAAa,EAA2B,IAAgE,CACjJ,IAAM,EAAiB,EAAuB,IAAI,EAAI,CAyBtD,OAxBK,EAID,MAAM,QAAQ,EAAU,CACtB,EAAU,SAAW,EAEhB,GAGL,EAAuB,EAAU,CAE5B,KADQ,EAAU,IAAK,GAAU,EAAgB,EAAO,EAAI,CAAC,CAAC,KAAK,GAAG,EAAa,IAAI,CAC3E,GAEd,EAAU,IAAK,GAAM,EAA+B,EAAE,MAAO,EAAE,SAAU,EAAgB,EAAuB,CAAC,CAAC,KAAK,EAAc,CAG1I,OAAO,GAAc,UAAY,OAAO,GAAc,SACjD,EAAgB,EAAW,EAAI,CAGpC,GAAW,SACN,EAA+B,EAAU,MAAO,EAAU,SAAU,EAAgB,EAAuB,CAE7G,GAvBE"}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { WhereOptions } from "sequelize";
|
|
2
|
-
|
|
3
|
-
//#region src/scopes/helpers/filter.helpers.d.ts
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Type representing possible condition values.
|
|
7
|
-
* Currently supporting strings and arrays of strings.
|
|
8
|
-
* More types to be added (TBA).
|
|
9
|
-
*/
|
|
10
|
-
type ConditionWithOperator = {
|
|
11
|
-
operator: string;
|
|
12
|
-
value: string;
|
|
13
|
-
};
|
|
14
|
-
type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];
|
|
15
|
-
//#endregion
|
|
16
|
-
export { ConditionValue };
|
|
17
|
-
//# sourceMappingURL=filter.helpers.d.cts.map
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { WhereOptions } from "sequelize";
|
|
2
|
-
|
|
3
|
-
//#region src/scopes/helpers/filter.helpers.d.ts
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Type representing possible condition values.
|
|
7
|
-
* Currently supporting strings and arrays of strings.
|
|
8
|
-
* More types to be added (TBA).
|
|
9
|
-
*/
|
|
10
|
-
type ConditionWithOperator = {
|
|
11
|
-
operator: string;
|
|
12
|
-
value: string;
|
|
13
|
-
};
|
|
14
|
-
type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];
|
|
15
|
-
//#endregion
|
|
16
|
-
export { ConditionValue };
|
|
17
|
-
//# sourceMappingURL=filter.helpers.d.ts.map
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
let e=function(e){return e.VALUES=`values`,e.ENTRIES=`entries`,e}({});const t=e=>Array.isArray(e)&&typeof e[0]==`string`,n=e=>[`true`,`false`].includes(e.toString()),r=e=>e instanceof Date||Object.prototype.toString.call(e)===`[object Date]`,i=(e,t)=>`to_jsonb(${e}::${t})`,a=e=>i(e,`text`),o=e=>i(e,`boolean`),s=e=>i(e,`numeric`),c=(e,t)=>r(t)?i(e,`timestamp`):e,l=` AND `,u=` OR `,d=`cv.value`,f=(e,t,i,a)=>{let o=`text`;r(e)?o=`date`:Number.isNaN(Number(e))?n(e)&&(o=`boolean`):o=`numeric`;let s=a.get(e);return`(jsonb_extract_path_text(ce.custom_fields, :${i})::${o}) ${t} :${s}`},p=e=>{let t=e;return n(e)?t=e===`true`:Number.isNaN(Number(e))||(t=Number(e)),t},m=(e,t)=>{let r=p(e),i=JSON.stringify({[t]:r}),a;return n(e)&&(a=`ce.custom_fields @> '${JSON.stringify({[t]:e})}'`),`
|
|
2
|
-
(
|
|
3
|
-
${a?`${a} OR`:``}
|
|
4
|
-
ce.custom_fields @> '${i}'
|
|
5
|
-
)
|
|
6
|
-
`},h=(t,n,r)=>{switch(t){case e.VALUES:return`
|
|
7
|
-
SELECT cv.model_id
|
|
8
|
-
FROM custom_field_values AS cv
|
|
9
|
-
INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id
|
|
10
|
-
${l}cd.model_type = '${n}'
|
|
11
|
-
WHERE ${r.join(u)}
|
|
12
|
-
${l}cv.deleted_at IS NULL${l}cd.deleted_at IS NULL
|
|
13
|
-
GROUP BY cv.model_id
|
|
14
|
-
HAVING COUNT(DISTINCT cv.custom_field_definition_id) = ${r.length}
|
|
15
|
-
`.replace(/\n/g,``);case e.ENTRIES:return`
|
|
16
|
-
SELECT ce.model_id
|
|
17
|
-
FROM custom_field_entries ce
|
|
18
|
-
JOIN custom_field_definitions cfd
|
|
19
|
-
ON ce.model_type = cfd.model_type
|
|
20
|
-
AND ce.entity_id = cfd.entity_id
|
|
21
|
-
WHERE
|
|
22
|
-
cfd.deleted_at IS NULL AND
|
|
23
|
-
${r.join(l)}
|
|
24
|
-
`;default:throw Error(`Invalid query type`)}},g=(t,n,r)=>{switch(t){case e.VALUES:return`(
|
|
25
|
-
SELECT value
|
|
26
|
-
FROM (SELECT cv.model_id, cv.value
|
|
27
|
-
FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd
|
|
28
|
-
ON cv.custom_field_definition_id = cd.id
|
|
29
|
-
${l}cd.model_type = '${n}'
|
|
30
|
-
WHERE cv.model_id = "${n}"."id"
|
|
31
|
-
${l}cd.name = :${r}
|
|
32
|
-
) AS CustomFieldAggregation
|
|
33
|
-
)
|
|
34
|
-
`;case e.ENTRIES:return`(
|
|
35
|
-
SELECT
|
|
36
|
-
customFields.value
|
|
37
|
-
FROM
|
|
38
|
-
custom_field_entries AS ce,
|
|
39
|
-
jsonb_each_text(custom_fields) AS customFields
|
|
40
|
-
WHERE
|
|
41
|
-
customFields.key = :${r}${l}
|
|
42
|
-
ce.model_type = '${n}'${l}
|
|
43
|
-
ce.model_id = "${n}"."id"
|
|
44
|
-
)
|
|
45
|
-
`;default:throw Error(`Invalid query type`)}},_=(e,r,i)=>{let f=i.get(e);if(!f)return!1;let p=`(cd.name = :${f})`;if(Array.isArray(r)){if(r.length===0)return!1;if(t(r)){let e=r.flatMap(e=>{let t=i.get(e);return n(e)?[a(`:${t}`),o(`:${t}`)]:Number.isNaN(Number(e))?a(`:${t}`):s(`:${t}`)}).join(`,`);return`(${p}${l}${d} IN (${e}))`}return r.map(e=>{let t=i.get(e.value),n=a(`:${t}`);return`(${p}${l}${c(d,e.value)} ${e.operator} ${n})`}).join(l)}if(typeof r==`string`||typeof r==`number`){let e=i.get(r),t=Number.isNaN(Number(r))?a(`:${e}`):s(`:${e}`),f=n(r)?`${u}${d} = ${o(`:${e}`)}`:``;return`(${p}${l}(${c(d,r)} = ${t}${f}))`}if(r?.operator){let e=i.get(r.value),t=a(`:${e}`);return`( ${p}${l}${c(d,r.value)} ${r.operator} ${t})`}return!1},v=(e,n,r)=>{let i=r.get(e);return i?Array.isArray(n)?n.length===0?!1:t(n)?`( ${n.map(t=>m(t,e)).join(`${u}\n`)})`:n.map(e=>f(e.value,e.operator,i,r)).join(l):typeof n==`string`||typeof n==`number`?m(n,e):n?.operator?f(n.value,n.operator,i,r):!1:!1};export{e as SubQueryType,v as formatConditionsForEntries,_ as formatConditionsForValues,h as getFilterCustomFieldsSubQuery,g as getSortCustomFieldsSubQuery};
|
|
46
|
-
//# sourceMappingURL=filter.helpers.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"filter.helpers.js","names":["CD_NAME_COLUMN: `${typeof CD_TABLE_ALIAS}.name`","CV_VALUE_COLUMN: `${typeof CV_TABLE_ALIAS}.value`","formattedValue: string | number | boolean"],"sources":["../../../src/scopes/helpers/filter.helpers.ts"],"sourcesContent":["import type { WhereOptions } from 'sequelize';\n\n/**\n * Type representing possible condition values.\n * Currently supporting strings and arrays of strings.\n * More types to be added (TBA).\n */\nexport type ConditionWithOperator = {\n operator: string;\n value: string;\n};\nexport type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];\n\nexport type CustomFieldSort = {\n field: string;\n direction: 'ASC' | 'DESC';\n}\n\nexport type CustomFieldFilterOptions = {\n where?: WhereOptions;\n replacements?: Record<string, string>;\n}\n\nexport enum SubQueryType {\n VALUES = 'values',\n ENTRIES = 'entries',\n}\n\nexport const isConditionStringArray = (input: any): input is string[] => Array.isArray(input) && typeof input[0] === 'string';\nexport const isBooleanString = (input: string): boolean => ['true', 'false'].includes(input.toString());\nexport const isDate = (input: any): input is Date => input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';\n\nexport const castValueToJsonb = (value: string, type: string) => `to_jsonb(${value}::${type})`;\nexport const castValueToJsonbText = (value: string): string => castValueToJsonb(value, 'text');\nexport const castValueToJsonbBoolean = (value: string): string => castValueToJsonb(value, 'boolean');\nexport const castValueToJsonbNumeric = (value: string): string => castValueToJsonb(value, 'numeric');\nexport const castIfNeeded = (columnName: string, conditionValue: string): string => {\n if (isDate(conditionValue)) {\n return castValueToJsonb(columnName, 'timestamp');\n }\n return columnName;\n};\n\nexport const AND_DELIMITER = ' AND ';\nexport const OR_DELIMITER = ' OR ';\nexport const CD_TABLE_ALIAS = 'cd';\nexport const CD_NAME_COLUMN: `${typeof CD_TABLE_ALIAS}.name` = `${CD_TABLE_ALIAS}.name`;\nexport const CV_TABLE_ALIAS = 'cv';\nexport const CV_VALUE_COLUMN: `${typeof CV_TABLE_ALIAS}.value` = `${CV_TABLE_ALIAS}.value`;\nexport const CE_TABLE_ALIAS = 'ce';\n\nconst getSingleConditionWithOperator = (value: any, operator: string, replacementKey: string, reverseReplacementsMap: Map<string, string>) => {\n let type = 'text';\n if (isDate(value)) {\n type = 'date';\n } else if (!Number.isNaN(Number(value))) {\n type = 'numeric';\n } else if (isBooleanString(value)) {\n type = 'boolean';\n }\n const replacedValue = reverseReplacementsMap.get(value);\n\n return `(jsonb_extract_path_text(${CE_TABLE_ALIAS}.custom_fields, :${replacementKey})::${type}) ${operator} :${replacedValue}`;\n};\n\nconst getFormattedValue = (value: string) => {\n let formattedValue: string | number | boolean = value;\n if (isBooleanString(value)) {\n formattedValue = value === 'true';\n } else if (!Number.isNaN(Number(value))) {\n formattedValue = Number(value);\n }\n\n return formattedValue;\n};\n\nconst getJSONSubQuery = (value: string, key: string) => {\n const formattedValue = getFormattedValue(value);\n const jsonQuery = JSON.stringify({ [key]: formattedValue });\n let jsonQueryWithStringBoolean;\n if (isBooleanString(value)) {\n jsonQueryWithStringBoolean = `${CE_TABLE_ALIAS}.custom_fields @> '${JSON.stringify({ [key]: value })}'`;\n }\n return `\n (\n ${jsonQueryWithStringBoolean ? `${jsonQueryWithStringBoolean} OR` : ''}\n ${CE_TABLE_ALIAS}.custom_fields @> '${jsonQuery}'\n )\n `;\n};\n\nexport const getFilterCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, conditionsStrings: Array<string | boolean>): string => {\n switch (queryType) {\n case SubQueryType.VALUES:\n return `\n SELECT ${CV_TABLE_ALIAS}.model_id\n FROM custom_field_values AS ${CV_TABLE_ALIAS}\n INNER JOIN custom_field_definitions AS ${CD_TABLE_ALIAS} ON ${CV_TABLE_ALIAS}.custom_field_definition_id = ${CD_TABLE_ALIAS}.id\n ${AND_DELIMITER}${CD_TABLE_ALIAS}.model_type = '${modelType}'\n WHERE ${conditionsStrings.join(OR_DELIMITER)}\n ${AND_DELIMITER}${CV_TABLE_ALIAS}.deleted_at IS NULL${AND_DELIMITER}${CD_TABLE_ALIAS}.deleted_at IS NULL\n GROUP BY ${CV_TABLE_ALIAS}.model_id\n HAVING COUNT(DISTINCT ${CV_TABLE_ALIAS}.custom_field_definition_id) = ${conditionsStrings.length}\n `.replace(/\\n/g, '');\n case SubQueryType.ENTRIES:\n return `\n SELECT ce.model_id\n FROM custom_field_entries ce\n JOIN custom_field_definitions cfd\n ON ce.model_type = cfd.model_type\n AND ce.entity_id = cfd.entity_id\n WHERE\n cfd.deleted_at IS NULL AND\n ${conditionsStrings.join(AND_DELIMITER)}\n `;\n default:\n throw new Error('Invalid query type');\n }\n};\n\nexport const getSortCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, replacementKey: string): string => {\n switch (queryType) {\n case SubQueryType.VALUES:\n return `(\n SELECT value\n FROM (SELECT cv.model_id, cv.value\n FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd\n ON cv.custom_field_definition_id = cd.id\n ${AND_DELIMITER}cd.model_type = '${modelType}'\n WHERE cv.model_id = \"${modelType}\".\"id\"\n ${AND_DELIMITER}cd.name = :${replacementKey}\n ) AS CustomFieldAggregation\n )\n `;\n case SubQueryType.ENTRIES:\n return `(\n SELECT\n customFields.value\n FROM\n custom_field_entries AS ${CE_TABLE_ALIAS},\n jsonb_each_text(custom_fields) AS customFields\n WHERE\n customFields.key = :${replacementKey}${AND_DELIMITER}\n ${CE_TABLE_ALIAS}.model_type = '${modelType}'${AND_DELIMITER}\n ${CE_TABLE_ALIAS}.model_id = \"${modelType}\".\"id\"\n )\n `;\n default:\n throw new Error('Invalid query type');\n }\n};\n\nexport const formatConditionsForValues = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>): false | string => {\n const replacementKey = reverseReplacementsMap.get(key);\n if (!replacementKey) {\n return false;\n }\n\n const columnCondition = `(${CD_NAME_COLUMN} = :${replacementKey})`;\n if (Array.isArray(condition)) {\n if (condition.length === 0) {\n // if empty array, the condition is ignored\n return false;\n }\n\n if (isConditionStringArray(condition)) {\n const values = condition.flatMap((v) => {\n const valRandom = reverseReplacementsMap.get(v);\n if (isBooleanString(v)) {\n return [castValueToJsonbText(`:${valRandom}`), castValueToJsonbBoolean(`:${valRandom}`)];\n }\n if (!Number.isNaN(Number(v))) {\n return castValueToJsonbNumeric(`:${valRandom}`);\n }\n return castValueToJsonbText(`:${valRandom}`);\n }).join(',');\n return `(${columnCondition}${AND_DELIMITER}${CV_VALUE_COLUMN} IN (${values}))`;\n }\n return condition.map((c) => {\n const valRep = reverseReplacementsMap.get(c.value);\n const valueAsJsonb = castValueToJsonbText(`:${valRep}`);\n\n return `(${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, c.value)} ${c.operator} ${valueAsJsonb})`;\n }).join(AND_DELIMITER);\n }\n if (typeof condition === 'string' || typeof condition === 'number') {\n const conditionRep = reverseReplacementsMap.get(condition);\n const valueAsJsonb = !Number.isNaN(Number(condition)) ? castValueToJsonbNumeric(`:${conditionRep}`) : castValueToJsonbText(`:${conditionRep}`);\n const valueAsJsonbBoolean = isBooleanString(condition) ? `${OR_DELIMITER}${CV_VALUE_COLUMN} = ${castValueToJsonbBoolean(`:${conditionRep}`)}` : '';\n return `(${columnCondition}${AND_DELIMITER}(${castIfNeeded(CV_VALUE_COLUMN, condition)} = ${valueAsJsonb}${valueAsJsonbBoolean}))`;\n }\n if (condition?.operator) {\n const valueRep = reverseReplacementsMap.get(condition.value);\n const valueAsJsonb = castValueToJsonbText(`:${valueRep}`);\n return `( ${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, condition.value)} ${condition.operator} ${valueAsJsonb})`;\n }\n return false;\n};\n\nexport const formatConditionsForEntries = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>): false | string => {\n const replacementKey = reverseReplacementsMap.get(key);\n if (!replacementKey) {\n return false;\n }\n\n if (Array.isArray(condition)) {\n if (condition.length === 0) {\n // if empty array, the condition is ignored\n return false;\n }\n\n if (isConditionStringArray(condition)) {\n const values = condition.map((value) => getJSONSubQuery(value, key)).join(`${OR_DELIMITER}\\n`);\n return `( ${values})`;\n }\n return condition.map((c) => getSingleConditionWithOperator(c.value, c.operator, replacementKey, reverseReplacementsMap)).join(AND_DELIMITER);\n }\n\n if (typeof condition === 'string' || typeof condition === 'number') {\n return getJSONSubQuery(condition, key);\n }\n\n if (condition?.operator) {\n return getSingleConditionWithOperator(condition.value, condition.operator, replacementKey, reverseReplacementsMap);\n }\n return false;\n};\n"],"mappings":"AAuBA,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,iBAGF,MAAa,EAA0B,GAAkC,MAAM,QAAQ,EAAM,EAAI,OAAO,EAAM,IAAO,SACxG,EAAmB,GAA2B,CAAC,OAAQ,QAAQ,CAAC,SAAS,EAAM,UAAU,CAAC,CAC1F,EAAU,GAA8B,aAAiB,MAAQ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,EAAe,EAAuB,IAAI,EAAU,CACpD,EAAgB,OAAO,MAAM,OAAO,EAAU,CAAC,CAAiD,EAAqB,IAAI,IAAe,CAAtF,EAAwB,IAAI,IAAe,CAC7F,EAAsB,EAAgB,EAAU,CAAG,GAAG,IAAe,EAAgB,KAAK,EAAwB,IAAI,IAAe,GAAK,GAChJ,MAAO,IAAI,IAAkB,EAAc,GAAG,EAAa,EAAiB,EAAU,CAAC,KAAK,IAAe,EAAoB,IAEjI,GAAI,GAAW,SAAU,CACvB,IAAM,EAAW,EAAuB,IAAI,EAAU,MAAM,CACtD,EAAe,EAAqB,IAAI,IAAW,CACzD,MAAO,KAAK,IAAkB,IAAgB,EAAa,EAAiB,EAAU,MAAM,CAAC,GAAG,EAAU,SAAS,GAAG,EAAa,GAErI,MAAO,IAGI,GAA8B,EAAa,EAA2B,IAAgE,CACjJ,IAAM,EAAiB,EAAuB,IAAI,EAAI,CAyBtD,OAxBK,EAID,MAAM,QAAQ,EAAU,CACtB,EAAU,SAAW,EAEhB,GAGL,EAAuB,EAAU,CAE5B,KADQ,EAAU,IAAK,GAAU,EAAgB,EAAO,EAAI,CAAC,CAAC,KAAK,GAAG,EAAa,IAAI,CAC3E,GAEd,EAAU,IAAK,GAAM,EAA+B,EAAE,MAAO,EAAE,SAAU,EAAgB,EAAuB,CAAC,CAAC,KAAK,EAAc,CAG1I,OAAO,GAAc,UAAY,OAAO,GAAc,SACjD,EAAgB,EAAW,EAAI,CAGpC,GAAW,SACN,EAA+B,EAAU,MAAO,EAAU,SAAU,EAAgB,EAAuB,CAE7G,GAvBE"}
|
package/dist/scopes/index.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=require(`./filter.cjs`);
|
package/dist/scopes/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{customFieldsFilterScope as e}from"./filter.js";export{};
|
package/dist/types/index.d.cts
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { ModelCtor, Sequelize } from "sequelize-typescript";
|
|
2
|
-
import { IncludeOptions } from "sequelize";
|
|
3
|
-
import { getUser } from "@autofleet/zehut";
|
|
4
|
-
|
|
5
|
-
//#region src/types/index.d.ts
|
|
6
|
-
type ModelFetcher = (name: string) => any;
|
|
7
|
-
type ModelOptions = {
|
|
8
|
-
/**
|
|
9
|
-
* Include options for the model
|
|
10
|
-
*/
|
|
11
|
-
include?: (entityIds: string | string[]) => IncludeOptions[];
|
|
12
|
-
/**
|
|
13
|
-
* Custom association for the model
|
|
14
|
-
* @param model - The model to associate with
|
|
15
|
-
*/
|
|
16
|
-
customAssociation?: (model: ModelCtor) => void;
|
|
17
|
-
/**
|
|
18
|
-
* Whether to use the entity id from the instance per scope attribute
|
|
19
|
-
*/
|
|
20
|
-
useEntityIdFromInclude?: boolean;
|
|
21
|
-
/**
|
|
22
|
-
* Which attributes to include in the model
|
|
23
|
-
*/
|
|
24
|
-
attributes?: string[];
|
|
25
|
-
};
|
|
26
|
-
type Models = {
|
|
27
|
-
name: string;
|
|
28
|
-
scopeAttributes: any[];
|
|
29
|
-
modelOptions?: ModelOptions;
|
|
30
|
-
creationWebhookHandler?: (instance: any) => any;
|
|
31
|
-
updateWebhookHandler?: (instance: any) => any;
|
|
32
|
-
deletionWebhookHandler?: (instance: any) => any;
|
|
33
|
-
};
|
|
34
|
-
type CustomFieldOptions = {
|
|
35
|
-
models: Models[];
|
|
36
|
-
databaseConfig: any;
|
|
37
|
-
getUser: typeof getUser;
|
|
38
|
-
sequelize?: Sequelize;
|
|
39
|
-
useCustomFieldsEntries?: boolean;
|
|
40
|
-
useValidators?: boolean;
|
|
41
|
-
};
|
|
42
|
-
//#endregion
|
|
43
|
-
export { CustomFieldOptions, ModelFetcher, Models };
|
|
44
|
-
//# sourceMappingURL=index.d.cts.map
|
package/dist/types/index.d.ts
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { IncludeOptions } from "sequelize";
|
|
2
|
-
import { ModelCtor, Sequelize } from "sequelize-typescript";
|
|
3
|
-
import { getUser } from "@autofleet/zehut";
|
|
4
|
-
|
|
5
|
-
//#region src/types/index.d.ts
|
|
6
|
-
type ModelFetcher = (name: string) => any;
|
|
7
|
-
type ModelOptions = {
|
|
8
|
-
/**
|
|
9
|
-
* Include options for the model
|
|
10
|
-
*/
|
|
11
|
-
include?: (entityIds: string | string[]) => IncludeOptions[];
|
|
12
|
-
/**
|
|
13
|
-
* Custom association for the model
|
|
14
|
-
* @param model - The model to associate with
|
|
15
|
-
*/
|
|
16
|
-
customAssociation?: (model: ModelCtor) => void;
|
|
17
|
-
/**
|
|
18
|
-
* Whether to use the entity id from the instance per scope attribute
|
|
19
|
-
*/
|
|
20
|
-
useEntityIdFromInclude?: boolean;
|
|
21
|
-
/**
|
|
22
|
-
* Which attributes to include in the model
|
|
23
|
-
*/
|
|
24
|
-
attributes?: string[];
|
|
25
|
-
};
|
|
26
|
-
type Models = {
|
|
27
|
-
name: string;
|
|
28
|
-
scopeAttributes: any[];
|
|
29
|
-
modelOptions?: ModelOptions;
|
|
30
|
-
creationWebhookHandler?: (instance: any) => any;
|
|
31
|
-
updateWebhookHandler?: (instance: any) => any;
|
|
32
|
-
deletionWebhookHandler?: (instance: any) => any;
|
|
33
|
-
};
|
|
34
|
-
type CustomFieldOptions = {
|
|
35
|
-
models: Models[];
|
|
36
|
-
databaseConfig: any;
|
|
37
|
-
getUser: typeof getUser;
|
|
38
|
-
sequelize?: Sequelize;
|
|
39
|
-
useCustomFieldsEntries?: boolean;
|
|
40
|
-
useValidators?: boolean;
|
|
41
|
-
};
|
|
42
|
-
//#endregion
|
|
43
|
-
export { CustomFieldOptions, ModelFetcher, Models };
|
|
44
|
-
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../../_virtual/rolldown_runtime.cjs`);let t=require(`@autofleet/common-types`);t=e.__toESM(t);const n=[`businessModelId`,`fleetId`,`demandSourceId`];let r=function(e){return e.NUMBER=`number`,e.BOOLEAN=`boolean`,e.DATE=`date`,e.DATETIME=`datetime`,e.TEXT=`text`,e.IMAGE=`image`,e.SELECT=`select`,e.STATUS=`status`,e.FILE=`file`,e}({});const i=t.customFields.CUSTOM_FIELDS_FILTER_SCOPE;exports.CUSTOM_FIELDS_FILTER_SCOPE=i,exports.CustomFieldDefinitionType=r,exports.supportedEntities=n;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE","customFields"],"sources":["../../../src/utils/constants/index.ts"],"sourcesContent":["import { customFields } from '@autofleet/common-types';\n\nexport const supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'] as const;\n\n/**\n * Supported custom field types\n */\nexport enum CustomFieldDefinitionType {\n NUMBER = 'number',\n BOOLEAN = 'boolean',\n DATE = 'date',\n DATETIME = 'datetime',\n TEXT = 'text',\n IMAGE = 'image',\n SELECT = 'select',\n STATUS = 'status',\n FILE = 'file',\n}\n\n// eslint-disable-next-line prefer-destructuring\nconst CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport {\n /** @deprecated Use the value from `@autofleet/common-types` instead */\n CUSTOM_FIELDS_FILTER_SCOPE,\n};\n"],"mappings":"+GAEA,MAAa,EAAoB,CAAC,kBAAmB,UAAW,iBAAiB,CAKjF,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,UACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,KAAA,OACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,cAIF,MAAMA,EAA6EC,EAAAA,aAAa"}
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { customFields } from "@autofleet/common-types";
|
|
2
|
-
|
|
3
|
-
//#region src/utils/constants/index.d.ts
|
|
4
|
-
declare const supportedEntities: readonly ["businessModelId", "fleetId", "demandSourceId"];
|
|
5
|
-
/**
|
|
6
|
-
* Supported custom field types
|
|
7
|
-
*/
|
|
8
|
-
declare enum CustomFieldDefinitionType {
|
|
9
|
-
NUMBER = "number",
|
|
10
|
-
BOOLEAN = "boolean",
|
|
11
|
-
DATE = "date",
|
|
12
|
-
DATETIME = "datetime",
|
|
13
|
-
TEXT = "text",
|
|
14
|
-
IMAGE = "image",
|
|
15
|
-
SELECT = "select",
|
|
16
|
-
STATUS = "status",
|
|
17
|
-
FILE = "file",
|
|
18
|
-
}
|
|
19
|
-
declare const CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE;
|
|
20
|
-
//#endregion
|
|
21
|
-
export { CUSTOM_FIELDS_FILTER_SCOPE, CustomFieldDefinitionType, supportedEntities };
|
|
22
|
-
//# sourceMappingURL=index.d.cts.map
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { customFields } from "@autofleet/common-types";
|
|
2
|
-
|
|
3
|
-
//#region src/utils/constants/index.d.ts
|
|
4
|
-
declare const supportedEntities: readonly ["businessModelId", "fleetId", "demandSourceId"];
|
|
5
|
-
/**
|
|
6
|
-
* Supported custom field types
|
|
7
|
-
*/
|
|
8
|
-
declare enum CustomFieldDefinitionType {
|
|
9
|
-
NUMBER = "number",
|
|
10
|
-
BOOLEAN = "boolean",
|
|
11
|
-
DATE = "date",
|
|
12
|
-
DATETIME = "datetime",
|
|
13
|
-
TEXT = "text",
|
|
14
|
-
IMAGE = "image",
|
|
15
|
-
SELECT = "select",
|
|
16
|
-
STATUS = "status",
|
|
17
|
-
FILE = "file",
|
|
18
|
-
}
|
|
19
|
-
declare const CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE;
|
|
20
|
-
//#endregion
|
|
21
|
-
export { CUSTOM_FIELDS_FILTER_SCOPE, CustomFieldDefinitionType, supportedEntities };
|
|
22
|
-
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{customFields as e}from"@autofleet/common-types";const t=[`businessModelId`,`fleetId`,`demandSourceId`];let n=function(e){return e.NUMBER=`number`,e.BOOLEAN=`boolean`,e.DATE=`date`,e.DATETIME=`datetime`,e.TEXT=`text`,e.IMAGE=`image`,e.SELECT=`select`,e.STATUS=`status`,e.FILE=`file`,e}({});const r=e.CUSTOM_FIELDS_FILTER_SCOPE;export{r as CUSTOM_FIELDS_FILTER_SCOPE,n as CustomFieldDefinitionType,t as supportedEntities};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE"],"sources":["../../../src/utils/constants/index.ts"],"sourcesContent":["import { customFields } from '@autofleet/common-types';\n\nexport const supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'] as const;\n\n/**\n * Supported custom field types\n */\nexport enum CustomFieldDefinitionType {\n NUMBER = 'number',\n BOOLEAN = 'boolean',\n DATE = 'date',\n DATETIME = 'datetime',\n TEXT = 'text',\n IMAGE = 'image',\n SELECT = 'select',\n STATUS = 'status',\n FILE = 'file',\n}\n\n// eslint-disable-next-line prefer-destructuring\nconst CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport {\n /** @deprecated Use the value from `@autofleet/common-types` instead */\n CUSTOM_FIELDS_FILTER_SCOPE,\n};\n"],"mappings":"uDAEA,MAAa,EAAoB,CAAC,kBAAmB,UAAW,iBAAiB,CAKjF,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,UACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,KAAA,OACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,cAIF,MAAMA,EAA6E,EAAa"}
|
package/dist/utils/db/index.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../../_virtual/rolldown_runtime.cjs`);let t=require(`sequelize`);t=e.__toESM(t);let n=require(`sequelize-typescript`);n=e.__toESM(n);var r=e=>{let t=process.env.NODE_ENV||`test`,r=e[t],i;return i=r.use_env_variable?new n.Sequelize(process.env[r.use_env_variable],r):new n.Sequelize(r.database,r.username,r.password,r),i};exports.default=r;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["env: string","sequelize: Sequelize","Sequelize","sequelize"],"sources":["../../../src/utils/db/index.ts"],"sourcesContent":["import { Sequelize } from 'sequelize-typescript';\nimport { QueryTypes } from 'sequelize';\n\nexport default (databaseConfig: any): Sequelize => {\n const ENV_DEV = 'test';\n const env: string = process.env.NODE_ENV || ENV_DEV;\n const config = databaseConfig[env];\n let sequelize: Sequelize;\n if (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable], config);\n } else {\n sequelize = new Sequelize(config.database, config.username, config.password, config);\n }\n return sequelize;\n};\n\nexport const createSequelizeMeta = (sequelize: Sequelize): Promise<{ name: string; }[]> => sequelize.query(`\nCREATE TABLE IF NOT EXISTS \"SequelizeMeta\" (\n name character varying(255) PRIMARY KEY\n);\n`, { type: QueryTypes.SELECT });\n"],"mappings":"sJAGA,IAAA,EAAgB,GAAmC,CAEjD,IAAMA,EAAc,QAAQ,IAAI,UADhB,OAEV,EAAS,EAAe,GAC1BC,EAMJ,MALA,CAGE,EAHE,EAAO,iBACG,IAAIC,EAAAA,UAAU,QAAQ,IAAI,EAAO,kBAAmB,EAAO,CAE3D,IAAIA,EAAAA,UAAU,EAAO,SAAU,EAAO,SAAU,EAAO,SAAU,EAAO,CAE/EC"}
|
package/dist/utils/db/index.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import"sequelize";import{Sequelize as e}from"sequelize-typescript";var t=t=>{let n=process.env.NODE_ENV||`test`,r=t[n],i;return i=r.use_env_variable?new e(process.env[r.use_env_variable],r):new e(r.database,r.username,r.password,r),i};export{t as default};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|