@strapi/database 5.51.1 → 5.52.0
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/dialects/mysql/database-inspector.js +1 -1
- package/dist/dialects/mysql/database-inspector.js.map +1 -1
- package/dist/dialects/mysql/database-inspector.mjs +1 -1
- package/dist/dialects/mysql/database-inspector.mjs.map +1 -1
- package/dist/dialects/mysql/index.js +2 -2
- package/dist/dialects/mysql/index.js.map +1 -1
- package/dist/dialects/mysql/index.mjs +2 -2
- package/dist/dialects/mysql/index.mjs.map +1 -1
- package/dist/entity-manager/index.js +30 -30
- package/dist/entity-manager/index.js.map +1 -1
- package/dist/entity-manager/index.mjs +30 -30
- package/dist/entity-manager/index.mjs.map +1 -1
- package/dist/entity-manager/relations-orderer.js +1 -1
- package/dist/entity-manager/relations-orderer.js.map +1 -1
- package/dist/entity-manager/relations-orderer.mjs +1 -1
- package/dist/entity-manager/relations-orderer.mjs.map +1 -1
- package/dist/fields/datetime.d.ts.map +1 -1
- package/dist/fields/datetime.js +6 -23
- package/dist/fields/datetime.js.map +1 -1
- package/dist/fields/datetime.mjs +6 -3
- package/dist/fields/datetime.mjs.map +1 -1
- package/dist/fields/index.d.ts.map +1 -1
- package/dist/fields/index.js +21 -8
- package/dist/fields/index.js.map +1 -1
- package/dist/fields/index.mjs +21 -4
- package/dist/fields/index.mjs.map +1 -1
- package/dist/fields/json.js +1 -1
- package/dist/fields/json.js.map +1 -1
- package/dist/fields/json.mjs +1 -1
- package/dist/fields/json.mjs.map +1 -1
- package/dist/fields/shared/parsers.js +1 -1
- package/dist/fields/shared/parsers.js.map +1 -1
- package/dist/fields/shared/parsers.mjs +1 -1
- package/dist/fields/shared/parsers.mjs.map +1 -1
- package/dist/fields/timestamp.d.ts.map +1 -1
- package/dist/fields/timestamp.js +5 -23
- package/dist/fields/timestamp.js.map +1 -1
- package/dist/fields/timestamp.mjs +5 -3
- package/dist/fields/timestamp.mjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/migrations/common.d.ts +12 -2
- package/dist/migrations/common.d.ts.map +1 -1
- package/dist/migrations/common.js.map +1 -1
- package/dist/migrations/common.mjs.map +1 -1
- package/dist/migrations/discover.d.ts +8 -0
- package/dist/migrations/discover.d.ts.map +1 -0
- package/dist/migrations/discover.js +49 -0
- package/dist/migrations/discover.js.map +1 -0
- package/dist/migrations/discover.mjs +42 -0
- package/dist/migrations/discover.mjs.map +1 -0
- package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.js +1 -1
- package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.js.map +1 -1
- package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.mjs +1 -1
- package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.mjs.map +1 -1
- package/dist/migrations/internal.d.ts.map +1 -1
- package/dist/migrations/internal.js +21 -40
- package/dist/migrations/internal.js.map +1 -1
- package/dist/migrations/internal.mjs +21 -40
- package/dist/migrations/internal.mjs.map +1 -1
- package/dist/migrations/resolver.d.ts +9 -0
- package/dist/migrations/resolver.d.ts.map +1 -0
- package/dist/migrations/resolver.js +53 -0
- package/dist/migrations/resolver.js.map +1 -0
- package/dist/migrations/resolver.mjs +45 -0
- package/dist/migrations/resolver.mjs.map +1 -0
- package/dist/migrations/runner.d.ts +24 -0
- package/dist/migrations/runner.d.ts.map +1 -0
- package/dist/migrations/runner.js +92 -0
- package/dist/migrations/runner.js.map +1 -0
- package/dist/migrations/runner.mjs +90 -0
- package/dist/migrations/runner.mjs.map +1 -0
- package/dist/migrations/users.d.ts.map +1 -1
- package/dist/migrations/users.js +22 -68
- package/dist/migrations/users.js.map +1 -1
- package/dist/migrations/users.mjs +21 -68
- package/dist/migrations/users.mjs.map +1 -1
- package/dist/query/helpers/populate/apply.js +2 -2
- package/dist/query/helpers/populate/apply.js.map +1 -1
- package/dist/query/helpers/populate/apply.mjs +2 -2
- package/dist/query/helpers/populate/apply.mjs.map +1 -1
- package/dist/query/helpers/search.d.ts +1 -0
- package/dist/query/helpers/search.d.ts.map +1 -1
- package/dist/query/helpers/search.js +1 -0
- package/dist/query/helpers/search.js.map +1 -1
- package/dist/query/helpers/search.mjs +1 -1
- package/dist/query/helpers/search.mjs.map +1 -1
- package/dist/query/helpers/transform.d.ts.map +1 -1
- package/dist/query/helpers/transform.js +4 -1
- package/dist/query/helpers/transform.js.map +1 -1
- package/dist/query/helpers/transform.mjs +4 -1
- package/dist/query/helpers/transform.mjs.map +1 -1
- package/dist/query/helpers/where.d.ts.map +1 -1
- package/dist/query/helpers/where.js +34 -14
- package/dist/query/helpers/where.js.map +1 -1
- package/dist/query/helpers/where.mjs +34 -14
- package/dist/query/helpers/where.mjs.map +1 -1
- package/package.json +6 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relations-orderer.js","sources":["../../src/entity-manager/relations-orderer.ts"],"sourcesContent":["import { castArray, maxBy } from 'lodash/fp';\nimport _ from 'lodash';\n\nimport { InvalidRelationError } from '../errors';\nimport type { ID } from '../types';\n\ninterface Link {\n id: ID;\n position?: { before?: ID; after?: ID; start?: true; end?: true };\n order?: number;\n __component?: string;\n}\n\ninterface OrderedLink extends Link {\n init?: boolean;\n order: number;\n}\n\n/**\n * When connecting relations, the order you connect them matters.\n *\n * Example, if you connect the following relations:\n * { id: 5, position: { before: 1 } }\n * { id: 1, position: { before: 2 } }\n * { id: 2, position: { end: true } }\n *\n * Going through the connect array, id 5 has to be connected before id 1,\n * so the order of id5 = id1 - 1. But the order value of id 1 is unknown.\n * The only way to know the order of id 1 is to connect it first.\n *\n * This function makes sure the relations are connected in the right order:\n * { id: 2, position: { end: true } }\n * { id: 1, position: { before: 2 } }\n * { id: 5, position: { before: 1 } }\n *\n */\nconst sortConnectArray = (connectArr: Link[], initialArr: Link[] = [], strictSort = true) => {\n const sortedConnect: Link[] = [];\n // Boolean to know if we have to recalculate the order of the relations\n let needsSorting = false;\n // Map to validate if relation is already in sortedConnect or DB.\n const relationInInitialArray = initialArr.reduce(\n (acc, rel) => ({ ...acc, [rel.id]: true }),\n {} as Record<ID, boolean>\n );\n // Map to store the first index where a relation id is connected\n const mappedRelations = connectArr.reduce(\n (mapper, relation: Link) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n\n if (!adjacentRelId || (!relationInInitialArray[adjacentRelId] && !mapper[adjacentRelId])) {\n needsSorting = true;\n }\n\n /**\n * We do not allow duplicate relations to be connected, so we need to check for uniqueness with components\n * Note that the id here includes the uid for polymorphic relations\n *\n * So for normal relations, the same id means the same relation\n * For component relations, it means the unique combo of (id, component name)\n */\n\n // Check if there's an existing relation with this id\n const existingRelation = mapper[relation.id];\n\n // Check if existing relation has a component or not\n const hasNoComponent = existingRelation && !('__component' in existingRelation);\n\n // Check if the existing relation has the same component as the new relation\n const hasSameComponent =\n existingRelation && existingRelation.__component === relation.__component;\n\n // If we have an existing relation that is not unique (no component or same component) we won't accept it\n if (existingRelation && (hasNoComponent || hasSameComponent)) {\n throw new InvalidRelationError(\n `The relation with id ${relation.id} is already connected. ` +\n 'You cannot connect the same relation twice.'\n );\n }\n\n return {\n [relation.id]: { ...relation, computed: false },\n ...mapper,\n };\n },\n {} as Record<ID, Link & { computed: boolean }>\n );\n\n // If we don't need to sort the connect array, we can return it as is\n if (!needsSorting) return connectArr;\n\n // Recursively compute in which order the relation should be connected\n const computeRelation = (relation: Link, relationsSeenInBranch: Record<ID, boolean>) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n const adjacentRelation = mappedRelations[adjacentRelId as ID];\n\n // If the relation has already been seen in the current branch,\n // it means there is a circular reference\n if (adjacentRelId && relationsSeenInBranch[adjacentRelId]) {\n throw new InvalidRelationError(\n 'A circular reference was found in the connect array. ' +\n 'One relation is trying to connect before/after another one that is trying to connect before/after it'\n );\n }\n\n // This relation has already been computed\n if (mappedRelations[relation.id]?.computed) {\n return;\n }\n\n mappedRelations[relation.id].computed = true;\n\n // Relation does not have a before or after attribute or is in the initial array\n if (!adjacentRelId || relationInInitialArray[adjacentRelId]) {\n sortedConnect.push(relation);\n return;\n }\n\n // Look if id is referenced elsewhere in the array\n if (mappedRelations[adjacentRelId]) {\n computeRelation(adjacentRelation, { ...relationsSeenInBranch, [relation.id]: true });\n sortedConnect.push(relation);\n } else if (strictSort) {\n // If we reach this point, it means that the adjacent relation is not in the connect array\n // and it is not in the database.\n throw new InvalidRelationError(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The relation with id ${adjacentRelId} needs to be connected first.`\n );\n } else {\n // We are in non-strict mode so we can push the relation.\n sortedConnect.push({ id: relation.id, position: { end: true } });\n }\n };\n\n // Iterate over connectArr and populate sortedConnect\n connectArr.forEach((relation) => computeRelation(relation, {}));\n\n return sortedConnect;\n};\n\n/**\n * Responsible for calculating the relations order when connecting them.\n *\n * The connect method takes an array of relations with positional attributes:\n * - before: the id of the relation to connect before\n * - after: the id of the relation to connect after\n * - end: it should be at the end\n * - start: it should be at the start\n *\n * Example:\n * - Having a connect array like:\n * [ { id: 4, before: 2 }, { id: 4, before: 3}, {id: 5, before: 4} ]\n * - With the initial relations:\n * [ { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * - Step by step, going through the connect array, the array of relations would be:\n * [ { id: 4, order: 3.5 }, { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 5, order: 3.5 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * - The final step would be to recalculate fractional order values.\n * [ { id: 2, order: 4 }, { id: 5, order: 3.33 }, { id: 4, order: 3.66 }, { id: 3, order: 10 } ]\n *\n * @param {Array<*>} initArr - array of relations to initialize the class with\n * @param {string} idColumn - the column name of the id\n * @param {string} orderColumn - the column name of the order\n * @param {boolean} strict - if true, will throw an error if a relation is connected adjacent to\n * another one that does not exist\n * @return {*}\n */\nconst relationsOrderer = <TRelation extends Record<string, ID | number | null>>(\n initArr: TRelation[],\n idColumn: keyof TRelation,\n orderColumn: keyof TRelation,\n strict?: boolean\n) => {\n const computedRelations: OrderedLink[] = _.sortBy(\n castArray(initArr ?? []).map((r) => ({\n init: true,\n id: r[idColumn] as ID,\n order: r[orderColumn] !== null && r[orderColumn] !== undefined ? Number(r[orderColumn]) : 1,\n })),\n 'order'\n );\n\n const maxOrder = maxBy('order', computedRelations)?.order || 0;\n\n const findRelation = (id: ID) => {\n const idx = computedRelations.findIndex((r) => r.id === id);\n return { idx, relation: computedRelations[idx] };\n };\n\n const removeRelation = (r: Link) => {\n const { idx } = findRelation(r.id);\n if (idx >= 0) {\n computedRelations.splice(idx, 1);\n }\n };\n\n const insertRelation = (r: Link) => {\n let idx;\n\n if (r.position?.before) {\n const { idx: beforeIdx, relation } = findRelation(r.position.before);\n if (relation.init) {\n const prevRelation = beforeIdx > 0 ? computedRelations[beforeIdx - 1] : null;\n r.order =\n prevRelation && prevRelation.order < relation.order\n ? (prevRelation.order + relation.order) / 2\n : relation.order - 0.5;\n } else {\n r.order = relation.order;\n }\n idx = beforeIdx;\n } else if (r.position?.after) {\n const { idx: afterIdx, relation } = findRelation(r.position.after);\n if (relation.init) {\n const nextRelation =\n afterIdx < computedRelations.length - 1 ? computedRelations[afterIdx + 1] : null;\n r.order =\n nextRelation && nextRelation.order > relation.order\n ? (relation.order + nextRelation.order) / 2\n : relation.order + 0.5;\n } else {\n r.order = relation.order;\n }\n idx = afterIdx + 1;\n } else if (r.position?.start) {\n if (computedRelations.length > 0) {\n const firstRelation = computedRelations[0];\n r.order = firstRelation.init ? firstRelation.order - 0.5 : firstRelation.order;\n } else {\n r.order = 0.5;\n }\n idx = 0;\n } else {\n r.order = maxOrder + 0.5;\n idx = computedRelations.length;\n }\n\n // Insert the relation in the array\n computedRelations.splice(idx, 0, r as OrderedLink);\n };\n\n return {\n disconnect(relations: Link | Link[]) {\n castArray(relations).forEach((relation) => {\n removeRelation(relation);\n });\n return this;\n },\n connect(relations: Link | Link[]) {\n sortConnectArray(castArray(relations), computedRelations, strict).forEach((relation) => {\n this.disconnect(relation);\n\n try {\n insertRelation(relation);\n } catch (err) {\n throw new Error(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The list of connect relations is not valid`\n );\n }\n });\n return this;\n },\n get() {\n return computedRelations;\n },\n /**\n * Get a map between the relation id and its order\n */\n getOrderMap() {\n const map: Record<ID, number> = {};\n const chunks = _(computedRelations).groupBy('order').value();\n const sortedKeys = Object.keys(chunks).sort((a, b) => parseFloat(a) - parseFloat(b));\n\n for (const orderStr of sortedKeys) {\n const relations = chunks[orderStr];\n let offset = 1;\n relations.forEach((relation) => {\n if (!relation.init) {\n map[relation.id] = parseFloat(orderStr) + (offset / (relations.length + 1)) * 0.49;\n offset += 1;\n }\n });\n }\n\n return map;\n },\n };\n};\n\nexport { relationsOrderer, sortConnectArray };\n"],"names":["sortConnectArray","connectArr","initialArr","strictSort","sortedConnect","needsSorting","relationInInitialArray","reduce","acc","rel","id","mappedRelations","mapper","relation","adjacentRelId","position","before","after","existingRelation","hasNoComponent","hasSameComponent","__component","InvalidRelationError","computed","computeRelation","relationsSeenInBranch","adjacentRelation","push","JSON","stringify","end","forEach","relationsOrderer","initArr","idColumn","orderColumn","strict","computedRelations","_","sortBy","castArray","map","r","init","order","undefined","Number","maxOrder","maxBy","findRelation","idx","findIndex","removeRelation","splice","insertRelation","beforeIdx","prevRelation","afterIdx","nextRelation","length","start","firstRelation","disconnect","relations","connect","err","Error","get","getOrderMap","chunks","groupBy","value","sortedKeys","Object","keys","sort","a","b","parseFloat","orderStr","offset"],"mappings":";;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;IAkBA,MAAMA,mBAAmB,CAACC,UAAAA,EAAoBC,aAAqB,EAAE,EAAEC,aAAa,IAAI,GAAA;AACtF,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AAYM,MAAM,CAACU,QAAAA,CAAS;AAClC,gBAAA,IAAIC,MAAAA,GAAS,CAAA;gBACbjB,SAAAA,CAAUhC,OAAO,CAAC,CAAClB,QAAAA,GAAAA;oBACjB,IAAI,CAACA,QAAAA,CAAS8B,IAAI,EAAE;AAClBF,wBAAAA,GAAG,CAAC5B,QAAAA,CAASH,EAAE,CAAC,GAAGoE,UAAAA,CAAWC,QAAAA,CAAAA,GAAY,MAACC,IAAUjB,SAAAA,CAAUJ,MAAM,GAAG,CAAA,CAAA,GAAM,IAAA;wBAC9EqB,MAAAA,IAAU,CAAA;AACZ,oBAAA;AACF,gBAAA,CAAA,CAAA;AACF,YAAA;YAEA,OAAOvC,GAAAA;AACT,QAAA;AACF,KAAA;AACF;;;;;"}
|
|
1
|
+
{"version":3,"file":"relations-orderer.js","sources":["../../src/entity-manager/relations-orderer.ts"],"sourcesContent":["import { castArray, maxBy } from 'lodash/fp';\nimport _ from 'lodash';\n\nimport { InvalidRelationError } from '../errors';\nimport type { ID } from '../types';\n\ninterface Link {\n id: ID;\n position?: { before?: ID; after?: ID; start?: true; end?: true };\n order?: number;\n __component?: string;\n}\n\ninterface OrderedLink extends Link {\n init?: boolean;\n order: number;\n}\n\n/**\n * When connecting relations, the order you connect them matters.\n *\n * Example, if you connect the following relations:\n * { id: 5, position: { before: 1 } }\n * { id: 1, position: { before: 2 } }\n * { id: 2, position: { end: true } }\n *\n * Going through the connect array, id 5 has to be connected before id 1,\n * so the order of id5 = id1 - 1. But the order value of id 1 is unknown.\n * The only way to know the order of id 1 is to connect it first.\n *\n * This function makes sure the relations are connected in the right order:\n * { id: 2, position: { end: true } }\n * { id: 1, position: { before: 2 } }\n * { id: 5, position: { before: 1 } }\n *\n */\nconst sortConnectArray = (connectArr: Link[], initialArr: Link[] = [], strictSort = true) => {\n const sortedConnect: Link[] = [];\n // Boolean to know if we have to recalculate the order of the relations\n let needsSorting = false;\n // Map to validate if relation is already in sortedConnect or DB.\n const relationInInitialArray = initialArr.reduce(\n (acc, rel) => ({ ...acc, [rel.id]: true }),\n {} as Record<ID, boolean>\n );\n // Map to store the first index where a relation id is connected\n const mappedRelations = connectArr.reduce(\n (mapper, relation: Link) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n\n if (!adjacentRelId || (!relationInInitialArray[adjacentRelId] && !mapper[adjacentRelId])) {\n needsSorting = true;\n }\n\n /**\n * We do not allow duplicate relations to be connected, so we need to check for uniqueness with components\n * Note that the id here includes the uid for polymorphic relations\n *\n * So for normal relations, the same id means the same relation\n * For component relations, it means the unique combo of (id, component name)\n */\n\n // Check if there's an existing relation with this id\n const existingRelation = mapper[relation.id];\n\n // Check if existing relation has a component or not\n const hasNoComponent = existingRelation && !('__component' in existingRelation);\n\n // Check if the existing relation has the same component as the new relation\n const hasSameComponent =\n existingRelation && existingRelation.__component === relation.__component;\n\n // If we have an existing relation that is not unique (no component or same component) we won't accept it\n if (existingRelation && (hasNoComponent || hasSameComponent)) {\n throw new InvalidRelationError(\n `The relation with id ${relation.id} is already connected. ` +\n 'You cannot connect the same relation twice.'\n );\n }\n\n return {\n [relation.id]: { ...relation, computed: false },\n ...mapper,\n };\n },\n {} as Record<ID, Link & { computed: boolean }>\n );\n\n // If we don't need to sort the connect array, we can return it as is\n if (!needsSorting) return connectArr;\n\n // Recursively compute in which order the relation should be connected\n const computeRelation = (relation: Link, relationsSeenInBranch: Record<ID, boolean>) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n const adjacentRelation = mappedRelations[adjacentRelId as ID];\n\n // If the relation has already been seen in the current branch,\n // it means there is a circular reference\n if (adjacentRelId && relationsSeenInBranch[adjacentRelId]) {\n throw new InvalidRelationError(\n 'A circular reference was found in the connect array. ' +\n 'One relation is trying to connect before/after another one that is trying to connect before/after it'\n );\n }\n\n // This relation has already been computed\n if (mappedRelations[relation.id]?.computed) {\n return;\n }\n\n mappedRelations[relation.id].computed = true;\n\n // Relation does not have a before or after attribute or is in the initial array\n if (!adjacentRelId || relationInInitialArray[adjacentRelId]) {\n sortedConnect.push(relation);\n return;\n }\n\n // Look if id is referenced elsewhere in the array\n if (mappedRelations[adjacentRelId]) {\n computeRelation(adjacentRelation, { ...relationsSeenInBranch, [relation.id]: true });\n sortedConnect.push(relation);\n } else if (strictSort) {\n // If we reach this point, it means that the adjacent relation is not in the connect array\n // and it is not in the database.\n throw new InvalidRelationError(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The relation with id ${adjacentRelId} needs to be connected first.`\n );\n } else {\n // We are in non-strict mode so we can push the relation.\n sortedConnect.push({ id: relation.id, position: { end: true } });\n }\n };\n\n // Iterate over connectArr and populate sortedConnect\n connectArr.forEach((relation) => computeRelation(relation, {}));\n\n return sortedConnect;\n};\n\n/**\n * Responsible for calculating the relations order when connecting them.\n *\n * The connect method takes an array of relations with positional attributes:\n * - before: the id of the relation to connect before\n * - after: the id of the relation to connect after\n * - end: it should be at the end\n * - start: it should be at the start\n *\n * Example:\n * - Having a connect array like:\n * [ { id: 4, before: 2 }, { id: 4, before: 3}, {id: 5, before: 4} ]\n * - With the initial relations:\n * [ { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * - Step by step, going through the connect array, the array of relations would be:\n * [ { id: 4, order: 3.5 }, { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 5, order: 3.5 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * - The final step would be to recalculate fractional order values.\n * [ { id: 2, order: 4 }, { id: 5, order: 3.33 }, { id: 4, order: 3.66 }, { id: 3, order: 10 } ]\n *\n * @param {Array<*>} initArr - array of relations to initialize the class with\n * @param {string} idColumn - the column name of the id\n * @param {string} orderColumn - the column name of the order\n * @param {boolean} strict - if true, will throw an error if a relation is connected adjacent to\n * another one that does not exist\n * @return {*}\n */\nconst relationsOrderer = <TRelation extends Record<string, ID | number | null>>(\n initArr: TRelation[],\n idColumn: keyof TRelation,\n orderColumn: keyof TRelation,\n strict?: boolean\n) => {\n const computedRelations: OrderedLink[] = _.sortBy(\n castArray(initArr ?? []).map((r) => ({\n init: true,\n id: r[idColumn] as ID,\n order: r[orderColumn] !== null && r[orderColumn] !== undefined ? Number(r[orderColumn]) : 1,\n })),\n 'order'\n );\n\n const maxOrder = maxBy('order', computedRelations)?.order || 0;\n\n const findRelation = (id: ID) => {\n const idx = computedRelations.findIndex((r) => r.id === id);\n return { idx, relation: computedRelations[idx] };\n };\n\n const removeRelation = (r: Link) => {\n const { idx } = findRelation(r.id);\n if (idx >= 0) {\n computedRelations.splice(idx, 1);\n }\n };\n\n const insertRelation = (r: Link) => {\n let idx;\n\n if (r.position?.before) {\n const { idx: beforeIdx, relation } = findRelation(r.position.before);\n if (relation.init) {\n const prevRelation = beforeIdx > 0 ? computedRelations[beforeIdx - 1] : null;\n r.order =\n prevRelation && prevRelation.order < relation.order\n ? (prevRelation.order + relation.order) / 2\n : relation.order - 0.5;\n } else {\n r.order = relation.order;\n }\n idx = beforeIdx;\n } else if (r.position?.after) {\n const { idx: afterIdx, relation } = findRelation(r.position.after);\n if (relation.init) {\n const nextRelation =\n afterIdx < computedRelations.length - 1 ? computedRelations[afterIdx + 1] : null;\n r.order =\n nextRelation && nextRelation.order > relation.order\n ? (relation.order + nextRelation.order) / 2\n : relation.order + 0.5;\n } else {\n r.order = relation.order;\n }\n idx = afterIdx + 1;\n } else if (r.position?.start) {\n if (computedRelations.length > 0) {\n const firstRelation = computedRelations[0];\n r.order = firstRelation.init ? firstRelation.order - 0.5 : firstRelation.order;\n } else {\n r.order = 0.5;\n }\n idx = 0;\n } else {\n r.order = maxOrder + 0.5;\n idx = computedRelations.length;\n }\n\n // Insert the relation in the array\n computedRelations.splice(idx, 0, r as OrderedLink);\n };\n\n return {\n disconnect(relations: Link | Link[]) {\n castArray(relations).forEach((relation) => {\n removeRelation(relation);\n });\n return this;\n },\n connect(relations: Link | Link[]) {\n sortConnectArray(castArray(relations), computedRelations, strict).forEach((relation) => {\n this.disconnect(relation);\n\n try {\n insertRelation(relation);\n } catch {\n throw new Error(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The list of connect relations is not valid`\n );\n }\n });\n return this;\n },\n get() {\n return computedRelations;\n },\n /**\n * Get a map between the relation id and its order\n */\n getOrderMap() {\n const map: Record<ID, number> = {};\n const chunks = _(computedRelations).groupBy('order').value();\n const sortedKeys = Object.keys(chunks).sort((a, b) => parseFloat(a) - parseFloat(b));\n\n for (const orderStr of sortedKeys) {\n const relations = chunks[orderStr];\n let offset = 1;\n relations.forEach((relation) => {\n if (!relation.init) {\n map[relation.id] = parseFloat(orderStr) + (offset / (relations.length + 1)) * 0.49;\n offset += 1;\n }\n });\n }\n\n return map;\n },\n };\n};\n\nexport { relationsOrderer, sortConnectArray };\n"],"names":["sortConnectArray","connectArr","initialArr","strictSort","sortedConnect","needsSorting","relationInInitialArray","reduce","acc","rel","id","mappedRelations","mapper","relation","adjacentRelId","position","before","after","existingRelation","hasNoComponent","hasSameComponent","__component","InvalidRelationError","computed","computeRelation","relationsSeenInBranch","adjacentRelation","push","JSON","stringify","end","forEach","relationsOrderer","initArr","idColumn","orderColumn","strict","computedRelations","_","sortBy","castArray","map","r","init","order","undefined","Number","maxOrder","maxBy","findRelation","idx","findIndex","removeRelation","splice","insertRelation","beforeIdx","prevRelation","afterIdx","nextRelation","length","start","firstRelation","disconnect","relations","connect","Error","get","getOrderMap","chunks","groupBy","value","sortedKeys","Object","keys","sort","a","b","parseFloat","orderStr","offset"],"mappings":";;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;IAkBA,MAAMA,mBAAmB,CAACC,UAAAA,EAAoBC,aAAqB,EAAE,EAAEC,aAAa,IAAI,GAAA;AACtF,IAAA,MAAMC,gBAAwB,EAAE;;AAEhC,IAAA,IAAIC,YAAAA,GAAe,KAAA;;AAEnB,IAAA,MAAMC,yBA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AClB,QAAAA,GAAAA;oBACjB,IAAI,CAACA,QAAAA,CAAS8B,IAAI,EAAE;AAClBF,wBAAAA,GAAG,CAAC5B,QAAAA,CAASH,EAAE,CAAC,GAAGmE,UAAAA,CAAWC,QAAAA,CAAAA,GAAY,MAACC,IAAUhB,SAAAA,CAAUJ,MAAM,GAAG,CAAA,CAAA,GAAM,IAAA;wBAC9EoB,MAAAA,IAAU,CAAA;AACZ,oBAAA;AACF,gBAAA,CAAA,CAAA;AACF,YAAA;YAEA,OAAOtC,GAAAA;AACT,QAAA;AACF,KAAA;AACF;;;;;"}
|
|
@@ -198,7 +198,7 @@ import InvalidRelationError from '../errors/invalid-relation.mjs';
|
|
|
198
198
|
this.disconnect(relation);
|
|
199
199
|
try {
|
|
200
200
|
insertRelation(relation);
|
|
201
|
-
} catch
|
|
201
|
+
} catch {
|
|
202
202
|
throw new Error(`There was a problem connecting relation with id ${relation.id} at position ${JSON.stringify(relation.position)}. The list of connect relations is not valid`);
|
|
203
203
|
}
|
|
204
204
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relations-orderer.mjs","sources":["../../src/entity-manager/relations-orderer.ts"],"sourcesContent":["import { castArray, maxBy } from 'lodash/fp';\nimport _ from 'lodash';\n\nimport { InvalidRelationError } from '../errors';\nimport type { ID } from '../types';\n\ninterface Link {\n id: ID;\n position?: { before?: ID; after?: ID; start?: true; end?: true };\n order?: number;\n __component?: string;\n}\n\ninterface OrderedLink extends Link {\n init?: boolean;\n order: number;\n}\n\n/**\n * When connecting relations, the order you connect them matters.\n *\n * Example, if you connect the following relations:\n * { id: 5, position: { before: 1 } }\n * { id: 1, position: { before: 2 } }\n * { id: 2, position: { end: true } }\n *\n * Going through the connect array, id 5 has to be connected before id 1,\n * so the order of id5 = id1 - 1. But the order value of id 1 is unknown.\n * The only way to know the order of id 1 is to connect it first.\n *\n * This function makes sure the relations are connected in the right order:\n * { id: 2, position: { end: true } }\n * { id: 1, position: { before: 2 } }\n * { id: 5, position: { before: 1 } }\n *\n */\nconst sortConnectArray = (connectArr: Link[], initialArr: Link[] = [], strictSort = true) => {\n const sortedConnect: Link[] = [];\n // Boolean to know if we have to recalculate the order of the relations\n let needsSorting = false;\n // Map to validate if relation is already in sortedConnect or DB.\n const relationInInitialArray = initialArr.reduce(\n (acc, rel) => ({ ...acc, [rel.id]: true }),\n {} as Record<ID, boolean>\n );\n // Map to store the first index where a relation id is connected\n const mappedRelations = connectArr.reduce(\n (mapper, relation: Link) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n\n if (!adjacentRelId || (!relationInInitialArray[adjacentRelId] && !mapper[adjacentRelId])) {\n needsSorting = true;\n }\n\n /**\n * We do not allow duplicate relations to be connected, so we need to check for uniqueness with components\n * Note that the id here includes the uid for polymorphic relations\n *\n * So for normal relations, the same id means the same relation\n * For component relations, it means the unique combo of (id, component name)\n */\n\n // Check if there's an existing relation with this id\n const existingRelation = mapper[relation.id];\n\n // Check if existing relation has a component or not\n const hasNoComponent = existingRelation && !('__component' in existingRelation);\n\n // Check if the existing relation has the same component as the new relation\n const hasSameComponent =\n existingRelation && existingRelation.__component === relation.__component;\n\n // If we have an existing relation that is not unique (no component or same component) we won't accept it\n if (existingRelation && (hasNoComponent || hasSameComponent)) {\n throw new InvalidRelationError(\n `The relation with id ${relation.id} is already connected. ` +\n 'You cannot connect the same relation twice.'\n );\n }\n\n return {\n [relation.id]: { ...relation, computed: false },\n ...mapper,\n };\n },\n {} as Record<ID, Link & { computed: boolean }>\n );\n\n // If we don't need to sort the connect array, we can return it as is\n if (!needsSorting) return connectArr;\n\n // Recursively compute in which order the relation should be connected\n const computeRelation = (relation: Link, relationsSeenInBranch: Record<ID, boolean>) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n const adjacentRelation = mappedRelations[adjacentRelId as ID];\n\n // If the relation has already been seen in the current branch,\n // it means there is a circular reference\n if (adjacentRelId && relationsSeenInBranch[adjacentRelId]) {\n throw new InvalidRelationError(\n 'A circular reference was found in the connect array. ' +\n 'One relation is trying to connect before/after another one that is trying to connect before/after it'\n );\n }\n\n // This relation has already been computed\n if (mappedRelations[relation.id]?.computed) {\n return;\n }\n\n mappedRelations[relation.id].computed = true;\n\n // Relation does not have a before or after attribute or is in the initial array\n if (!adjacentRelId || relationInInitialArray[adjacentRelId]) {\n sortedConnect.push(relation);\n return;\n }\n\n // Look if id is referenced elsewhere in the array\n if (mappedRelations[adjacentRelId]) {\n computeRelation(adjacentRelation, { ...relationsSeenInBranch, [relation.id]: true });\n sortedConnect.push(relation);\n } else if (strictSort) {\n // If we reach this point, it means that the adjacent relation is not in the connect array\n // and it is not in the database.\n throw new InvalidRelationError(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The relation with id ${adjacentRelId} needs to be connected first.`\n );\n } else {\n // We are in non-strict mode so we can push the relation.\n sortedConnect.push({ id: relation.id, position: { end: true } });\n }\n };\n\n // Iterate over connectArr and populate sortedConnect\n connectArr.forEach((relation) => computeRelation(relation, {}));\n\n return sortedConnect;\n};\n\n/**\n * Responsible for calculating the relations order when connecting them.\n *\n * The connect method takes an array of relations with positional attributes:\n * - before: the id of the relation to connect before\n * - after: the id of the relation to connect after\n * - end: it should be at the end\n * - start: it should be at the start\n *\n * Example:\n * - Having a connect array like:\n * [ { id: 4, before: 2 }, { id: 4, before: 3}, {id: 5, before: 4} ]\n * - With the initial relations:\n * [ { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * - Step by step, going through the connect array, the array of relations would be:\n * [ { id: 4, order: 3.5 }, { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 5, order: 3.5 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * - The final step would be to recalculate fractional order values.\n * [ { id: 2, order: 4 }, { id: 5, order: 3.33 }, { id: 4, order: 3.66 }, { id: 3, order: 10 } ]\n *\n * @param {Array<*>} initArr - array of relations to initialize the class with\n * @param {string} idColumn - the column name of the id\n * @param {string} orderColumn - the column name of the order\n * @param {boolean} strict - if true, will throw an error if a relation is connected adjacent to\n * another one that does not exist\n * @return {*}\n */\nconst relationsOrderer = <TRelation extends Record<string, ID | number | null>>(\n initArr: TRelation[],\n idColumn: keyof TRelation,\n orderColumn: keyof TRelation,\n strict?: boolean\n) => {\n const computedRelations: OrderedLink[] = _.sortBy(\n castArray(initArr ?? []).map((r) => ({\n init: true,\n id: r[idColumn] as ID,\n order: r[orderColumn] !== null && r[orderColumn] !== undefined ? Number(r[orderColumn]) : 1,\n })),\n 'order'\n );\n\n const maxOrder = maxBy('order', computedRelations)?.order || 0;\n\n const findRelation = (id: ID) => {\n const idx = computedRelations.findIndex((r) => r.id === id);\n return { idx, relation: computedRelations[idx] };\n };\n\n const removeRelation = (r: Link) => {\n const { idx } = findRelation(r.id);\n if (idx >= 0) {\n computedRelations.splice(idx, 1);\n }\n };\n\n const insertRelation = (r: Link) => {\n let idx;\n\n if (r.position?.before) {\n const { idx: beforeIdx, relation } = findRelation(r.position.before);\n if (relation.init) {\n const prevRelation = beforeIdx > 0 ? computedRelations[beforeIdx - 1] : null;\n r.order =\n prevRelation && prevRelation.order < relation.order\n ? (prevRelation.order + relation.order) / 2\n : relation.order - 0.5;\n } else {\n r.order = relation.order;\n }\n idx = beforeIdx;\n } else if (r.position?.after) {\n const { idx: afterIdx, relation } = findRelation(r.position.after);\n if (relation.init) {\n const nextRelation =\n afterIdx < computedRelations.length - 1 ? computedRelations[afterIdx + 1] : null;\n r.order =\n nextRelation && nextRelation.order > relation.order\n ? (relation.order + nextRelation.order) / 2\n : relation.order + 0.5;\n } else {\n r.order = relation.order;\n }\n idx = afterIdx + 1;\n } else if (r.position?.start) {\n if (computedRelations.length > 0) {\n const firstRelation = computedRelations[0];\n r.order = firstRelation.init ? firstRelation.order - 0.5 : firstRelation.order;\n } else {\n r.order = 0.5;\n }\n idx = 0;\n } else {\n r.order = maxOrder + 0.5;\n idx = computedRelations.length;\n }\n\n // Insert the relation in the array\n computedRelations.splice(idx, 0, r as OrderedLink);\n };\n\n return {\n disconnect(relations: Link | Link[]) {\n castArray(relations).forEach((relation) => {\n removeRelation(relation);\n });\n return this;\n },\n connect(relations: Link | Link[]) {\n sortConnectArray(castArray(relations), computedRelations, strict).forEach((relation) => {\n this.disconnect(relation);\n\n try {\n insertRelation(relation);\n } catch (err) {\n throw new Error(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The list of connect relations is not valid`\n );\n }\n });\n return this;\n },\n get() {\n return computedRelations;\n },\n /**\n * Get a map between the relation id and its order\n */\n getOrderMap() {\n const map: Record<ID, number> = {};\n const chunks = _(computedRelations).groupBy('order').value();\n const sortedKeys = Object.keys(chunks).sort((a, b) => parseFloat(a) - parseFloat(b));\n\n for (const orderStr of sortedKeys) {\n const relations = chunks[orderStr];\n let offset = 1;\n relations.forEach((relation) => {\n if (!relation.init) {\n map[relation.id] = parseFloat(orderStr) + (offset / (relations.length + 1)) * 0.49;\n offset += 1;\n }\n });\n }\n\n return map;\n },\n };\n};\n\nexport { relationsOrderer, sortConnectArray };\n"],"names":["sortConnectArray","connectArr","initialArr","strictSort","sortedConnect","needsSorting","relationInInitialArray","reduce","acc","rel","id","mappedRelations","mapper","relation","adjacentRelId","position","before","after","existingRelation","hasNoComponent","hasSameComponent","__component","InvalidRelationError","computed","computeRelation","relationsSeenInBranch","adjacentRelation","push","JSON","stringify","end","forEach","relationsOrderer","initArr","idColumn","orderColumn","strict","computedRelations","_","sortBy","castArray","map","r","init","order","undefined","Number","maxOrder","maxBy","findRelation","idx","findIndex","removeRelation","splice","insertRelation","beforeIdx","prevRelation","afterIdx","nextRelation","length","start","firstRelation","disconnect","relations","connect","err","Error","get","getOrderMap","chunks","groupBy","value","sortedKeys","Object","keys","sort","a","b","parseFloat","orderStr","offset"],"mappings":";;;;AAkBA;;;;;;;;;;;;;;;;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AWD,CAAAA,CAAAA,CAAAA;YAEjF,KAAK,MAAME,YAAYP,UAAAA,CAAY;gBACjC,MAAMT,SAAAA,GAAYM,MAAM,CAACU,QAAAA,CAAS;AAClC,gBAAA,IAAIC,MAAAA,GAAS,CAAA;gBACbjB,SAAAA,CAAUhC,OAAO,CAAC,CAAClB,QAAAA,GAAAA;oBACjB,IAAI,CAACA,QAAAA,CAAS8B,IAAI,EAAE;AAClBF,wBAAAA,GAAG,CAAC5B,QAAAA,CAASH,EAAE,CAAC,GAAGoE,UAAAA,CAAWC,QAAAA,CAAAA,GAAY,MAACC,IAAUjB,SAAAA,CAAUJ,MAAM,GAAG,CAAA,CAAA,GAAM,IAAA;wBAC9EqB,MAAAA,IAAU,CAAA;AACZ,oBAAA;AACF,gBAAA,CAAA,CAAA;AACF,YAAA;YAEA,OAAOvC,GAAAA;AACT,QAAA;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"relations-orderer.mjs","sources":["../../src/entity-manager/relations-orderer.ts"],"sourcesContent":["import { castArray, maxBy } from 'lodash/fp';\nimport _ from 'lodash';\n\nimport { InvalidRelationError } from '../errors';\nimport type { ID } from '../types';\n\ninterface Link {\n id: ID;\n position?: { before?: ID; after?: ID; start?: true; end?: true };\n order?: number;\n __component?: string;\n}\n\ninterface OrderedLink extends Link {\n init?: boolean;\n order: number;\n}\n\n/**\n * When connecting relations, the order you connect them matters.\n *\n * Example, if you connect the following relations:\n * { id: 5, position: { before: 1 } }\n * { id: 1, position: { before: 2 } }\n * { id: 2, position: { end: true } }\n *\n * Going through the connect array, id 5 has to be connected before id 1,\n * so the order of id5 = id1 - 1. But the order value of id 1 is unknown.\n * The only way to know the order of id 1 is to connect it first.\n *\n * This function makes sure the relations are connected in the right order:\n * { id: 2, position: { end: true } }\n * { id: 1, position: { before: 2 } }\n * { id: 5, position: { before: 1 } }\n *\n */\nconst sortConnectArray = (connectArr: Link[], initialArr: Link[] = [], strictSort = true) => {\n const sortedConnect: Link[] = [];\n // Boolean to know if we have to recalculate the order of the relations\n let needsSorting = false;\n // Map to validate if relation is already in sortedConnect or DB.\n const relationInInitialArray = initialArr.reduce(\n (acc, rel) => ({ ...acc, [rel.id]: true }),\n {} as Record<ID, boolean>\n );\n // Map to store the first index where a relation id is connected\n const mappedRelations = connectArr.reduce(\n (mapper, relation: Link) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n\n if (!adjacentRelId || (!relationInInitialArray[adjacentRelId] && !mapper[adjacentRelId])) {\n needsSorting = true;\n }\n\n /**\n * We do not allow duplicate relations to be connected, so we need to check for uniqueness with components\n * Note that the id here includes the uid for polymorphic relations\n *\n * So for normal relations, the same id means the same relation\n * For component relations, it means the unique combo of (id, component name)\n */\n\n // Check if there's an existing relation with this id\n const existingRelation = mapper[relation.id];\n\n // Check if existing relation has a component or not\n const hasNoComponent = existingRelation && !('__component' in existingRelation);\n\n // Check if the existing relation has the same component as the new relation\n const hasSameComponent =\n existingRelation && existingRelation.__component === relation.__component;\n\n // If we have an existing relation that is not unique (no component or same component) we won't accept it\n if (existingRelation && (hasNoComponent || hasSameComponent)) {\n throw new InvalidRelationError(\n `The relation with id ${relation.id} is already connected. ` +\n 'You cannot connect the same relation twice.'\n );\n }\n\n return {\n [relation.id]: { ...relation, computed: false },\n ...mapper,\n };\n },\n {} as Record<ID, Link & { computed: boolean }>\n );\n\n // If we don't need to sort the connect array, we can return it as is\n if (!needsSorting) return connectArr;\n\n // Recursively compute in which order the relation should be connected\n const computeRelation = (relation: Link, relationsSeenInBranch: Record<ID, boolean>) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n const adjacentRelation = mappedRelations[adjacentRelId as ID];\n\n // If the relation has already been seen in the current branch,\n // it means there is a circular reference\n if (adjacentRelId && relationsSeenInBranch[adjacentRelId]) {\n throw new InvalidRelationError(\n 'A circular reference was found in the connect array. ' +\n 'One relation is trying to connect before/after another one that is trying to connect before/after it'\n );\n }\n\n // This relation has already been computed\n if (mappedRelations[relation.id]?.computed) {\n return;\n }\n\n mappedRelations[relation.id].computed = true;\n\n // Relation does not have a before or after attribute or is in the initial array\n if (!adjacentRelId || relationInInitialArray[adjacentRelId]) {\n sortedConnect.push(relation);\n return;\n }\n\n // Look if id is referenced elsewhere in the array\n if (mappedRelations[adjacentRelId]) {\n computeRelation(adjacentRelation, { ...relationsSeenInBranch, [relation.id]: true });\n sortedConnect.push(relation);\n } else if (strictSort) {\n // If we reach this point, it means that the adjacent relation is not in the connect array\n // and it is not in the database.\n throw new InvalidRelationError(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The relation with id ${adjacentRelId} needs to be connected first.`\n );\n } else {\n // We are in non-strict mode so we can push the relation.\n sortedConnect.push({ id: relation.id, position: { end: true } });\n }\n };\n\n // Iterate over connectArr and populate sortedConnect\n connectArr.forEach((relation) => computeRelation(relation, {}));\n\n return sortedConnect;\n};\n\n/**\n * Responsible for calculating the relations order when connecting them.\n *\n * The connect method takes an array of relations with positional attributes:\n * - before: the id of the relation to connect before\n * - after: the id of the relation to connect after\n * - end: it should be at the end\n * - start: it should be at the start\n *\n * Example:\n * - Having a connect array like:\n * [ { id: 4, before: 2 }, { id: 4, before: 3}, {id: 5, before: 4} ]\n * - With the initial relations:\n * [ { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * - Step by step, going through the connect array, the array of relations would be:\n * [ { id: 4, order: 3.5 }, { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 5, order: 3.5 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * - The final step would be to recalculate fractional order values.\n * [ { id: 2, order: 4 }, { id: 5, order: 3.33 }, { id: 4, order: 3.66 }, { id: 3, order: 10 } ]\n *\n * @param {Array<*>} initArr - array of relations to initialize the class with\n * @param {string} idColumn - the column name of the id\n * @param {string} orderColumn - the column name of the order\n * @param {boolean} strict - if true, will throw an error if a relation is connected adjacent to\n * another one that does not exist\n * @return {*}\n */\nconst relationsOrderer = <TRelation extends Record<string, ID | number | null>>(\n initArr: TRelation[],\n idColumn: keyof TRelation,\n orderColumn: keyof TRelation,\n strict?: boolean\n) => {\n const computedRelations: OrderedLink[] = _.sortBy(\n castArray(initArr ?? []).map((r) => ({\n init: true,\n id: r[idColumn] as ID,\n order: r[orderColumn] !== null && r[orderColumn] !== undefined ? Number(r[orderColumn]) : 1,\n })),\n 'order'\n );\n\n const maxOrder = maxBy('order', computedRelations)?.order || 0;\n\n const findRelation = (id: ID) => {\n const idx = computedRelations.findIndex((r) => r.id === id);\n return { idx, relation: computedRelations[idx] };\n };\n\n const removeRelation = (r: Link) => {\n const { idx } = findRelation(r.id);\n if (idx >= 0) {\n computedRelations.splice(idx, 1);\n }\n };\n\n const insertRelation = (r: Link) => {\n let idx;\n\n if (r.position?.before) {\n const { idx: beforeIdx, relation } = findRelation(r.position.before);\n if (relation.init) {\n const prevRelation = beforeIdx > 0 ? computedRelations[beforeIdx - 1] : null;\n r.order =\n prevRelation && prevRelation.order < relation.order\n ? (prevRelation.order + relation.order) / 2\n : relation.order - 0.5;\n } else {\n r.order = relation.order;\n }\n idx = beforeIdx;\n } else if (r.position?.after) {\n const { idx: afterIdx, relation } = findRelation(r.position.after);\n if (relation.init) {\n const nextRelation =\n afterIdx < computedRelations.length - 1 ? computedRelations[afterIdx + 1] : null;\n r.order =\n nextRelation && nextRelation.order > relation.order\n ? (relation.order + nextRelation.order) / 2\n : relation.order + 0.5;\n } else {\n r.order = relation.order;\n }\n idx = afterIdx + 1;\n } else if (r.position?.start) {\n if (computedRelations.length > 0) {\n const firstRelation = computedRelations[0];\n r.order = firstRelation.init ? firstRelation.order - 0.5 : firstRelation.order;\n } else {\n r.order = 0.5;\n }\n idx = 0;\n } else {\n r.order = maxOrder + 0.5;\n idx = computedRelations.length;\n }\n\n // Insert the relation in the array\n computedRelations.splice(idx, 0, r as OrderedLink);\n };\n\n return {\n disconnect(relations: Link | Link[]) {\n castArray(relations).forEach((relation) => {\n removeRelation(relation);\n });\n return this;\n },\n connect(relations: Link | Link[]) {\n sortConnectArray(castArray(relations), computedRelations, strict).forEach((relation) => {\n this.disconnect(relation);\n\n try {\n insertRelation(relation);\n } catch {\n throw new Error(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The list of connect relations is not valid`\n );\n }\n });\n return this;\n },\n get() {\n return computedRelations;\n },\n /**\n * Get a map between the relation id and its order\n */\n getOrderMap() {\n const map: Record<ID, number> = {};\n const chunks = _(computedRelations).groupBy('order').value();\n const sortedKeys = Object.keys(chunks).sort((a, b) => parseFloat(a) - parseFloat(b));\n\n for (const orderStr of sortedKeys) {\n const relations = chunks[orderStr];\n let offset = 1;\n relations.forEach((relation) => {\n if (!relation.init) {\n map[relation.id] = parseFloat(orderStr) + (offset / (relations.length + 1)) * 0.49;\n offset += 1;\n }\n });\n }\n\n return map;\n },\n };\n};\n\nexport { relationsOrderer, sortConnectArray };\n"],"names":["sortConnectArray","connectArr","initialArr","strictSort","sortedConnect","needsSorting","relationInInitialArray","reduce","acc","rel","id","mappedRelations","mapper","relation","adjacentRelId","position","before","after","existingRelation","hasNoComponent","hasSameComponent","__component","InvalidRelationError","computed","computeRelation","relationsSeenInBranch","adjacentRelation","push","JSON","stringify","end","forEach","relationsOrderer","initArr","idColumn","orderColumn","strict","computedRelations","_","sortBy","castArray","map","r","init","order","undefined","Number","maxOrder","maxBy","findRelation","idx","findIndex","removeRelation","splice","insertRelation","beforeIdx","prevRelation","afterIdx","nextRelation","length","start","firstRelation","disconnect","relations","connect","Error","get","getOrderMap","chunks","groupBy","value","sortedKeys","Object","keys","sort","a","b","parseFloat","orderStr","offset"],"mappings":";;;;AAkBA;;;;;;;;;;;;;;;;;IAkBA,MAAMA,mBAAmB,CAACC,UAAAA,EAAoBC,aAAqB,EAAE,EAAEC,aAAa,IAAI,GAAA;AACtF,IAAA,MAAM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AS;AAClC,gBAAA,IAAIC,MAAAA,GAAS,CAAA;gBACbhB,SAAAA,CAAUhC,OAAO,CAAC,CAAClB,QAAAA,GAAAA;oBACjB,IAAI,CAACA,QAAAA,CAAS8B,IAAI,EAAE;AAClBF,wBAAAA,GAAG,CAAC5B,QAAAA,CAASH,EAAE,CAAC,GAAGmE,UAAAA,CAAWC,QAAAA,CAAAA,GAAY,MAACC,IAAUhB,SAAAA,CAAUJ,MAAM,GAAG,CAAA,CAAA,GAAM,IAAA;wBAC9EoB,MAAAA,IAAU,CAAA;AACZ,oBAAA;AACF,gBAAA,CAAA,CAAA;AACF,YAAA;YAEA,OAAOtC,GAAAA;AACT,QAAA;AACF,KAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datetime.d.ts","sourceRoot":"","sources":["../../src/fields/datetime.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"datetime.d.ts","sourceRoot":"","sources":["../../src/fields/datetime.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,SAAS,CAAC;AAE5B,MAAM,CAAC,OAAO,OAAO,aAAc,SAAQ,KAAK;IAC9C,IAAI,CAAC,KAAK,EAAE,OAAO;IAInB,MAAM,CAAC,KAAK,EAAE,OAAO;CAQtB"}
|
package/dist/fields/datetime.js
CHANGED
|
@@ -1,36 +1,19 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var dateFns = require('date-fns');
|
|
4
3
|
var parsers = require('./shared/parsers.js');
|
|
5
4
|
var field = require('./field.js');
|
|
6
5
|
|
|
7
|
-
function _interopNamespace(e) {
|
|
8
|
-
if (e && e.__esModule) return e;
|
|
9
|
-
var n = Object.create(null);
|
|
10
|
-
if (e) {
|
|
11
|
-
Object.keys(e).forEach(function (k) {
|
|
12
|
-
if (k !== 'default') {
|
|
13
|
-
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
14
|
-
Object.defineProperty(n, k, d.get ? d : {
|
|
15
|
-
enumerable: true,
|
|
16
|
-
get: function () { return e[k]; }
|
|
17
|
-
});
|
|
18
|
-
}
|
|
19
|
-
});
|
|
20
|
-
}
|
|
21
|
-
n.default = e;
|
|
22
|
-
return Object.freeze(n);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
var dateFns__namespace = /*#__PURE__*/_interopNamespace(dateFns);
|
|
26
|
-
|
|
27
6
|
class DatetimeField extends field {
|
|
28
7
|
toDB(value) {
|
|
29
8
|
return parsers.parseDateTimeOrTimestamp(value);
|
|
30
9
|
}
|
|
31
10
|
fromDB(value) {
|
|
32
|
-
|
|
33
|
-
|
|
11
|
+
// Drivers already hand back a `Date` for timestamp columns, so the constructor was
|
|
12
|
+
// re-parsing a value that had just been parsed — once per datetime column of every
|
|
13
|
+
// row. For a `Date`, `dateFns.isValid` reduces to a NaN check on the timestamp, which
|
|
14
|
+
// is what this does without the argument normalisation date-fns performs first.
|
|
15
|
+
const cast = value instanceof Date ? value : new Date(value);
|
|
16
|
+
return Number.isNaN(cast.getTime()) ? null : cast.toISOString();
|
|
34
17
|
}
|
|
35
18
|
}
|
|
36
19
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datetime.js","sources":["../../src/fields/datetime.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"datetime.js","sources":["../../src/fields/datetime.ts"],"sourcesContent":["import { parseDateTimeOrTimestamp } from './shared/parsers';\nimport Field from './field';\n\nexport default class DatetimeField extends Field {\n toDB(value: unknown) {\n return parseDateTimeOrTimestamp(value);\n }\n\n fromDB(value: unknown) {\n // Drivers already hand back a `Date` for timestamp columns, so the constructor was\n // re-parsing a value that had just been parsed — once per datetime column of every\n // row. For a `Date`, `dateFns.isValid` reduces to a NaN check on the timestamp, which\n // is what this does without the argument normalisation date-fns performs first.\n const cast = value instanceof Date ? value : new Date(value as any);\n return Number.isNaN(cast.getTime()) ? null : cast.toISOString();\n }\n}\n"],"names":["DatetimeField","Field","toDB","value","parseDateTimeOrTimestamp","fromDB","cast","Date","Number","isNaN","getTime","toISOString"],"mappings":";;;;;AAGe,MAAMA,aAAAA,SAAsBC,KAAAA,CAAAA;AACzCC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;AACnB,QAAA,OAAOC,gCAAAA,CAAyBD,KAAAA,CAAAA;AAClC,IAAA;AAEAE,IAAAA,MAAAA,CAAOF,KAAc,EAAE;;;;;AAKrB,QAAA,MAAMG,IAAAA,GAAOH,KAAAA,YAAiBI,IAAAA,GAAOJ,KAAAA,GAAQ,IAAII,IAAAA,CAAKJ,KAAAA,CAAAA;QACtD,OAAOK,MAAAA,CAAOC,KAAK,CAACH,IAAAA,CAAKI,OAAO,EAAA,CAAA,GAAM,IAAA,GAAOJ,KAAKK,WAAW,EAAA;AAC/D,IAAA;AACF;;;;"}
|
package/dist/fields/datetime.mjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import * as dateFns from 'date-fns';
|
|
2
1
|
import { parseDateTimeOrTimestamp } from './shared/parsers.mjs';
|
|
3
2
|
import Field from './field.mjs';
|
|
4
3
|
|
|
@@ -7,8 +6,12 @@ class DatetimeField extends Field {
|
|
|
7
6
|
return parseDateTimeOrTimestamp(value);
|
|
8
7
|
}
|
|
9
8
|
fromDB(value) {
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
// Drivers already hand back a `Date` for timestamp columns, so the constructor was
|
|
10
|
+
// re-parsing a value that had just been parsed — once per datetime column of every
|
|
11
|
+
// row. For a `Date`, `dateFns.isValid` reduces to a NaN check on the timestamp, which
|
|
12
|
+
// is what this does without the argument normalisation date-fns performs first.
|
|
13
|
+
const cast = value instanceof Date ? value : new Date(value);
|
|
14
|
+
return Number.isNaN(cast.getTime()) ? null : cast.toISOString();
|
|
12
15
|
}
|
|
13
16
|
}
|
|
14
17
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datetime.mjs","sources":["../../src/fields/datetime.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"datetime.mjs","sources":["../../src/fields/datetime.ts"],"sourcesContent":["import { parseDateTimeOrTimestamp } from './shared/parsers';\nimport Field from './field';\n\nexport default class DatetimeField extends Field {\n toDB(value: unknown) {\n return parseDateTimeOrTimestamp(value);\n }\n\n fromDB(value: unknown) {\n // Drivers already hand back a `Date` for timestamp columns, so the constructor was\n // re-parsing a value that had just been parsed — once per datetime column of every\n // row. For a `Date`, `dateFns.isValid` reduces to a NaN check on the timestamp, which\n // is what this does without the argument normalisation date-fns performs first.\n const cast = value instanceof Date ? value : new Date(value as any);\n return Number.isNaN(cast.getTime()) ? null : cast.toISOString();\n }\n}\n"],"names":["DatetimeField","Field","toDB","value","parseDateTimeOrTimestamp","fromDB","cast","Date","Number","isNaN","getTime","toISOString"],"mappings":";;;AAGe,MAAMA,aAAAA,SAAsBC,KAAAA,CAAAA;AACzCC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;AACnB,QAAA,OAAOC,wBAAAA,CAAyBD,KAAAA,CAAAA;AAClC,IAAA;AAEAE,IAAAA,MAAAA,CAAOF,KAAc,EAAE;;;;;AAKrB,QAAA,MAAMG,IAAAA,GAAOH,KAAAA,YAAiBI,IAAAA,GAAOJ,KAAAA,GAAQ,IAAII,IAAAA,CAAKJ,KAAAA,CAAAA;QACtD,OAAOK,MAAAA,CAAOC,KAAK,CAACH,IAAAA,CAAKI,OAAO,EAAA,CAAA,GAAM,IAAA,GAAOJ,KAAKK,WAAW,EAAA;AAC/D,IAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/fields/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/fields/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,SAAS,CAAC;AAW5B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAmC1C,eAAO,MAAM,WAAW,GAAI,WAAW,SAAS,KAAG,KAoBlD,CAAC"}
|
package/dist/fields/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var _ = require('lodash/fp');
|
|
4
3
|
var field = require('./field.js');
|
|
5
4
|
var string = require('./string.js');
|
|
6
5
|
var json = require('./json.js');
|
|
@@ -12,10 +11,6 @@ var datetime = require('./datetime.js');
|
|
|
12
11
|
var timestamp = require('./timestamp.js');
|
|
13
12
|
var boolean = require('./boolean.js');
|
|
14
13
|
|
|
15
|
-
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
16
|
-
|
|
17
|
-
var ___default = /*#__PURE__*/_interopDefault(_);
|
|
18
|
-
|
|
19
14
|
const typeToFieldMap = {
|
|
20
15
|
increments: field,
|
|
21
16
|
password: string,
|
|
@@ -37,12 +32,30 @@ const typeToFieldMap = {
|
|
|
37
32
|
boolean: boolean,
|
|
38
33
|
blocks: json
|
|
39
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* One instance per type, shared.
|
|
37
|
+
*
|
|
38
|
+
* Every call site constructs with an empty config and no subclass reads `this.config` —
|
|
39
|
+
* `toDB`/`fromDB` are pure functions of their argument — so the instances are
|
|
40
|
+
* interchangeable. They were being allocated once per scalar column per row, which on a
|
|
41
|
+
* page of entities with relations and components ran into the thousands and showed up as
|
|
42
|
+
* GC pressure rather than as time in this function.
|
|
43
|
+
*/ const fieldInstances = new Map();
|
|
40
44
|
const createField = (attribute)=>{
|
|
41
45
|
const { type } = attribute;
|
|
42
|
-
|
|
43
|
-
|
|
46
|
+
const cached = fieldInstances.get(type);
|
|
47
|
+
if (cached !== undefined) {
|
|
48
|
+
return cached;
|
|
49
|
+
}
|
|
50
|
+
// Own-property check: `type` comes from a schema, and an inherited key such as
|
|
51
|
+
// `constructor` must not resolve to a field class. This is also what lodash's `has`
|
|
52
|
+
// did, minus the path parsing it ran on every column of every row.
|
|
53
|
+
if (!Object.prototype.hasOwnProperty.call(typeToFieldMap, type)) {
|
|
54
|
+
throw new Error(`Undefined field for type ${type}`);
|
|
44
55
|
}
|
|
45
|
-
|
|
56
|
+
const field = new typeToFieldMap[type]({});
|
|
57
|
+
fieldInstances.set(type, field);
|
|
58
|
+
return field;
|
|
46
59
|
};
|
|
47
60
|
|
|
48
61
|
exports.createField = createField;
|
package/dist/fields/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/fields/index.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../src/fields/index.ts"],"sourcesContent":["import Field from './field';\nimport StringField from './string';\nimport JSONField from './json';\nimport BigIntegerField from './biginteger';\nimport NumberField from './number';\nimport DateField from './date';\nimport TimeField from './time';\nimport DatetimeField from './datetime';\nimport TimestampField from './timestamp';\nimport BooleanField from './boolean';\n\nimport type { Attribute } from '../types';\n\nconst typeToFieldMap: Record<string, typeof Field> = {\n increments: Field,\n password: StringField,\n email: StringField,\n string: StringField,\n uid: StringField,\n richtext: StringField,\n text: StringField,\n enumeration: StringField,\n json: JSONField,\n biginteger: BigIntegerField,\n integer: NumberField,\n float: NumberField,\n decimal: NumberField,\n date: DateField,\n time: TimeField,\n datetime: DatetimeField,\n timestamp: TimestampField,\n boolean: BooleanField,\n blocks: JSONField,\n};\n\n/**\n * One instance per type, shared.\n *\n * Every call site constructs with an empty config and no subclass reads `this.config` —\n * `toDB`/`fromDB` are pure functions of their argument — so the instances are\n * interchangeable. They were being allocated once per scalar column per row, which on a\n * page of entities with relations and components ran into the thousands and showed up as\n * GC pressure rather than as time in this function.\n */\nconst fieldInstances = new Map<string, Field>();\n\nexport const createField = (attribute: Attribute): Field => {\n const { type } = attribute;\n\n const cached = fieldInstances.get(type);\n\n if (cached !== undefined) {\n return cached;\n }\n\n // Own-property check: `type` comes from a schema, and an inherited key such as\n // `constructor` must not resolve to a field class. This is also what lodash's `has`\n // did, minus the path parsing it ran on every column of every row.\n if (!Object.prototype.hasOwnProperty.call(typeToFieldMap, type)) {\n throw new Error(`Undefined field for type ${type}`);\n }\n\n const field = new typeToFieldMap[type]({});\n fieldInstances.set(type, field);\n\n return field;\n};\n"],"names":["typeToFieldMap","increments","Field","password","StringField","email","string","uid","richtext","text","enumeration","json","JSONField","biginteger","BigIntegerField","integer","NumberField","float","decimal","date","DateField","time","TimeField","datetime","DatetimeField","timestamp","TimestampField","boolean","BooleanField","blocks","fieldInstances","Map","createField","attribute","type","cached","get","undefined","Object","prototype","hasOwnProperty","call","Error","field","set"],"mappings":";;;;;;;;;;;;;AAaA,MAAMA,cAAAA,GAA+C;IACnDC,UAAAA,EAAYC,KAAAA;IACZC,QAAAA,EAAUC,MAAAA;IACVC,KAAAA,EAAOD,MAAAA;IACPE,MAAAA,EAAQF,MAAAA;IACRG,GAAAA,EAAKH,MAAAA;IACLI,QAAAA,EAAUJ,MAAAA;IACVK,IAAAA,EAAML,MAAAA;IACNM,WAAAA,EAAaN,MAAAA;IACbO,IAAAA,EAAMC,IAAAA;IACNC,UAAAA,EAAYC,UAAAA;IACZC,OAAAA,EAASC,MAAAA;IACTC,KAAAA,EAAOD,MAAAA;IACPE,OAAAA,EAASF,MAAAA;IACTG,IAAAA,EAAMC,IAAAA;IACNC,IAAAA,EAAMC,IAAAA;IACNC,QAAAA,EAAUC,QAAAA;IACVC,SAAAA,EAAWC,SAAAA;IACXC,OAAAA,EAASC,OAAAA;IACTC,MAAAA,EAAQjB;AACV,CAAA;AAEA;;;;;;;;IASA,MAAMkB,iBAAiB,IAAIC,GAAAA,EAAAA;AAEpB,MAAMC,cAAc,CAACC,SAAAA,GAAAA;IAC1B,MAAM,EAAEC,IAAI,EAAE,GAAGD,SAAAA;IAEjB,MAAME,MAAAA,GAASL,cAAAA,CAAeM,GAAG,CAACF,IAAAA,CAAAA;AAElC,IAAA,IAAIC,WAAWE,SAAAA,EAAW;QACxB,OAAOF,MAAAA;AACT,IAAA;;;;IAKA,IAAI,CAACG,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACzC,cAAAA,EAAgBkC,IAAAA,CAAAA,EAAO;AAC/D,QAAA,MAAM,IAAIQ,KAAAA,CAAM,CAAC,yBAAyB,EAAER,IAAAA,CAAAA,CAAM,CAAA;AACpD,IAAA;AAEA,IAAA,MAAMS,QAAQ,IAAI3C,cAAc,CAACkC,IAAAA,CAAK,CAAC,EAAC,CAAA;IACxCJ,cAAAA,CAAec,GAAG,CAACV,IAAAA,EAAMS,KAAAA,CAAAA;IAEzB,OAAOA,KAAAA;AACT;;;;"}
|
package/dist/fields/index.mjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import _ from 'lodash/fp';
|
|
2
1
|
import Field from './field.mjs';
|
|
3
2
|
import StringField from './string.mjs';
|
|
4
3
|
import JSONField from './json.mjs';
|
|
@@ -31,12 +30,30 @@ const typeToFieldMap = {
|
|
|
31
30
|
boolean: BooleanField,
|
|
32
31
|
blocks: JSONField
|
|
33
32
|
};
|
|
33
|
+
/**
|
|
34
|
+
* One instance per type, shared.
|
|
35
|
+
*
|
|
36
|
+
* Every call site constructs with an empty config and no subclass reads `this.config` —
|
|
37
|
+
* `toDB`/`fromDB` are pure functions of their argument — so the instances are
|
|
38
|
+
* interchangeable. They were being allocated once per scalar column per row, which on a
|
|
39
|
+
* page of entities with relations and components ran into the thousands and showed up as
|
|
40
|
+
* GC pressure rather than as time in this function.
|
|
41
|
+
*/ const fieldInstances = new Map();
|
|
34
42
|
const createField = (attribute)=>{
|
|
35
43
|
const { type } = attribute;
|
|
36
|
-
|
|
37
|
-
|
|
44
|
+
const cached = fieldInstances.get(type);
|
|
45
|
+
if (cached !== undefined) {
|
|
46
|
+
return cached;
|
|
38
47
|
}
|
|
39
|
-
|
|
48
|
+
// Own-property check: `type` comes from a schema, and an inherited key such as
|
|
49
|
+
// `constructor` must not resolve to a field class. This is also what lodash's `has`
|
|
50
|
+
// did, minus the path parsing it ran on every column of every row.
|
|
51
|
+
if (!Object.prototype.hasOwnProperty.call(typeToFieldMap, type)) {
|
|
52
|
+
throw new Error(`Undefined field for type ${type}`);
|
|
53
|
+
}
|
|
54
|
+
const field = new typeToFieldMap[type]({});
|
|
55
|
+
fieldInstances.set(type, field);
|
|
56
|
+
return field;
|
|
40
57
|
};
|
|
41
58
|
|
|
42
59
|
export { createField };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../src/fields/index.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../src/fields/index.ts"],"sourcesContent":["import Field from './field';\nimport StringField from './string';\nimport JSONField from './json';\nimport BigIntegerField from './biginteger';\nimport NumberField from './number';\nimport DateField from './date';\nimport TimeField from './time';\nimport DatetimeField from './datetime';\nimport TimestampField from './timestamp';\nimport BooleanField from './boolean';\n\nimport type { Attribute } from '../types';\n\nconst typeToFieldMap: Record<string, typeof Field> = {\n increments: Field,\n password: StringField,\n email: StringField,\n string: StringField,\n uid: StringField,\n richtext: StringField,\n text: StringField,\n enumeration: StringField,\n json: JSONField,\n biginteger: BigIntegerField,\n integer: NumberField,\n float: NumberField,\n decimal: NumberField,\n date: DateField,\n time: TimeField,\n datetime: DatetimeField,\n timestamp: TimestampField,\n boolean: BooleanField,\n blocks: JSONField,\n};\n\n/**\n * One instance per type, shared.\n *\n * Every call site constructs with an empty config and no subclass reads `this.config` —\n * `toDB`/`fromDB` are pure functions of their argument — so the instances are\n * interchangeable. They were being allocated once per scalar column per row, which on a\n * page of entities with relations and components ran into the thousands and showed up as\n * GC pressure rather than as time in this function.\n */\nconst fieldInstances = new Map<string, Field>();\n\nexport const createField = (attribute: Attribute): Field => {\n const { type } = attribute;\n\n const cached = fieldInstances.get(type);\n\n if (cached !== undefined) {\n return cached;\n }\n\n // Own-property check: `type` comes from a schema, and an inherited key such as\n // `constructor` must not resolve to a field class. This is also what lodash's `has`\n // did, minus the path parsing it ran on every column of every row.\n if (!Object.prototype.hasOwnProperty.call(typeToFieldMap, type)) {\n throw new Error(`Undefined field for type ${type}`);\n }\n\n const field = new typeToFieldMap[type]({});\n fieldInstances.set(type, field);\n\n return field;\n};\n"],"names":["typeToFieldMap","increments","Field","password","StringField","email","string","uid","richtext","text","enumeration","json","JSONField","biginteger","BigIntegerField","integer","NumberField","float","decimal","date","DateField","time","TimeField","datetime","DatetimeField","timestamp","TimestampField","boolean","BooleanField","blocks","fieldInstances","Map","createField","attribute","type","cached","get","undefined","Object","prototype","hasOwnProperty","call","Error","field","set"],"mappings":";;;;;;;;;;;AAaA,MAAMA,cAAAA,GAA+C;IACnDC,UAAAA,EAAYC,KAAAA;IACZC,QAAAA,EAAUC,WAAAA;IACVC,KAAAA,EAAOD,WAAAA;IACPE,MAAAA,EAAQF,WAAAA;IACRG,GAAAA,EAAKH,WAAAA;IACLI,QAAAA,EAAUJ,WAAAA;IACVK,IAAAA,EAAML,WAAAA;IACNM,WAAAA,EAAaN,WAAAA;IACbO,IAAAA,EAAMC,SAAAA;IACNC,UAAAA,EAAYC,eAAAA;IACZC,OAAAA,EAASC,WAAAA;IACTC,KAAAA,EAAOD,WAAAA;IACPE,OAAAA,EAASF,WAAAA;IACTG,IAAAA,EAAMC,SAAAA;IACNC,IAAAA,EAAMC,SAAAA;IACNC,QAAAA,EAAUC,aAAAA;IACVC,SAAAA,EAAWC,cAAAA;IACXC,OAAAA,EAASC,YAAAA;IACTC,MAAAA,EAAQjB;AACV,CAAA;AAEA;;;;;;;;IASA,MAAMkB,iBAAiB,IAAIC,GAAAA,EAAAA;AAEpB,MAAMC,cAAc,CAACC,SAAAA,GAAAA;IAC1B,MAAM,EAAEC,IAAI,EAAE,GAAGD,SAAAA;IAEjB,MAAME,MAAAA,GAASL,cAAAA,CAAeM,GAAG,CAACF,IAAAA,CAAAA;AAElC,IAAA,IAAIC,WAAWE,SAAAA,EAAW;QACxB,OAAOF,MAAAA;AACT,IAAA;;;;IAKA,IAAI,CAACG,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACzC,cAAAA,EAAgBkC,IAAAA,CAAAA,EAAO;AAC/D,QAAA,MAAM,IAAIQ,KAAAA,CAAM,CAAC,yBAAyB,EAAER,IAAAA,CAAAA,CAAM,CAAA;AACpD,IAAA;AAEA,IAAA,MAAMS,QAAQ,IAAI3C,cAAc,CAACkC,IAAAA,CAAK,CAAC,EAAC,CAAA;IACxCJ,cAAAA,CAAec,GAAG,CAACV,IAAAA,EAAMS,KAAAA,CAAAA;IAEzB,OAAOA,KAAAA;AACT;;;;"}
|
package/dist/fields/json.js
CHANGED
package/dist/fields/json.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.js","sources":["../../src/fields/json.ts"],"sourcesContent":["import Field from './field';\n\nexport default class JSONField extends Field {\n toDB(value: unknown) {\n if (value == null) {\n return null;\n }\n\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n\n return value;\n }\n\n fromDB(value: unknown) {\n try {\n if (typeof value === 'string') {\n const parsedValue = JSON.parse(value);\n\n /**\n * On Strapi 5 until 5.0.0-rc.7, the values were accidentally stringified twice when saved,\n * so in those cases we need to parse them twice to retrieve the actual value.\n */\n if (typeof parsedValue === 'string') {\n return JSON.parse(parsedValue);\n }\n\n return parsedValue;\n }\n } catch
|
|
1
|
+
{"version":3,"file":"json.js","sources":["../../src/fields/json.ts"],"sourcesContent":["import Field from './field';\n\nexport default class JSONField extends Field {\n toDB(value: unknown) {\n if (value == null) {\n return null;\n }\n\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n\n return value;\n }\n\n fromDB(value: unknown) {\n try {\n if (typeof value === 'string') {\n const parsedValue = JSON.parse(value);\n\n /**\n * On Strapi 5 until 5.0.0-rc.7, the values were accidentally stringified twice when saved,\n * so in those cases we need to parse them twice to retrieve the actual value.\n */\n if (typeof parsedValue === 'string') {\n return JSON.parse(parsedValue);\n }\n\n return parsedValue;\n }\n } catch {\n // Just return the value if it's not a valid JSON string\n return value;\n }\n\n return value;\n }\n}\n"],"names":["JSONField","Field","toDB","value","JSON","stringify","fromDB","parsedValue","parse"],"mappings":";;;;AAEe,MAAMA,SAAAA,SAAkBC,KAAAA,CAAAA;AACrCC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;AACnB,QAAA,IAAIA,SAAS,IAAA,EAAM;YACjB,OAAO,IAAA;AACT,QAAA;QAEA,IAAI,OAAOA,UAAU,QAAA,EAAU;YAC7B,OAAOC,IAAAA,CAAKC,SAAS,CAACF,KAAAA,CAAAA;AACxB,QAAA;QAEA,OAAOA,KAAAA;AACT,IAAA;AAEAG,IAAAA,MAAAA,CAAOH,KAAc,EAAE;QACrB,IAAI;YACF,IAAI,OAAOA,UAAU,QAAA,EAAU;gBAC7B,MAAMI,WAAAA,GAAcH,IAAAA,CAAKI,KAAK,CAACL,KAAAA,CAAAA;AAE/B;;;YAIA,IAAI,OAAOI,WAAAA,KAAgB,QAAA,EAAU;oBACnC,OAAOH,IAAAA,CAAKI,KAAK,CAACD,WAAAA,CAAAA;AACpB,gBAAA;gBAEA,OAAOA,WAAAA;AACT,YAAA;AACF,QAAA,CAAA,CAAE,OAAM;;YAEN,OAAOJ,KAAAA;AACT,QAAA;QAEA,OAAOA,KAAAA;AACT,IAAA;AACF;;;;"}
|
package/dist/fields/json.mjs
CHANGED
package/dist/fields/json.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.mjs","sources":["../../src/fields/json.ts"],"sourcesContent":["import Field from './field';\n\nexport default class JSONField extends Field {\n toDB(value: unknown) {\n if (value == null) {\n return null;\n }\n\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n\n return value;\n }\n\n fromDB(value: unknown) {\n try {\n if (typeof value === 'string') {\n const parsedValue = JSON.parse(value);\n\n /**\n * On Strapi 5 until 5.0.0-rc.7, the values were accidentally stringified twice when saved,\n * so in those cases we need to parse them twice to retrieve the actual value.\n */\n if (typeof parsedValue === 'string') {\n return JSON.parse(parsedValue);\n }\n\n return parsedValue;\n }\n } catch
|
|
1
|
+
{"version":3,"file":"json.mjs","sources":["../../src/fields/json.ts"],"sourcesContent":["import Field from './field';\n\nexport default class JSONField extends Field {\n toDB(value: unknown) {\n if (value == null) {\n return null;\n }\n\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n\n return value;\n }\n\n fromDB(value: unknown) {\n try {\n if (typeof value === 'string') {\n const parsedValue = JSON.parse(value);\n\n /**\n * On Strapi 5 until 5.0.0-rc.7, the values were accidentally stringified twice when saved,\n * so in those cases we need to parse them twice to retrieve the actual value.\n */\n if (typeof parsedValue === 'string') {\n return JSON.parse(parsedValue);\n }\n\n return parsedValue;\n }\n } catch {\n // Just return the value if it's not a valid JSON string\n return value;\n }\n\n return value;\n }\n}\n"],"names":["JSONField","Field","toDB","value","JSON","stringify","fromDB","parsedValue","parse"],"mappings":";;AAEe,MAAMA,SAAAA,SAAkBC,KAAAA,CAAAA;AACrCC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;AACnB,QAAA,IAAIA,SAAS,IAAA,EAAM;YACjB,OAAO,IAAA;AACT,QAAA;QAEA,IAAI,OAAOA,UAAU,QAAA,EAAU;YAC7B,OAAOC,IAAAA,CAAKC,SAAS,CAACF,KAAAA,CAAAA;AACxB,QAAA;QAEA,OAAOA,KAAAA;AACT,IAAA;AAEAG,IAAAA,MAAAA,CAAOH,KAAc,EAAE;QACrB,IAAI;YACF,IAAI,OAAOA,UAAU,QAAA,EAAU;gBAC7B,MAAMI,WAAAA,GAAcH,IAAAA,CAAKI,KAAK,CAACL,KAAAA,CAAAA;AAE/B;;;YAIA,IAAI,OAAOI,WAAAA,KAAgB,QAAA,EAAU;oBACnC,OAAOH,IAAAA,CAAKI,KAAK,CAACD,WAAAA,CAAAA;AACpB,gBAAA;gBAEA,OAAOA,WAAAA;AACT,YAAA;AACF,QAAA,CAAA,CAAE,OAAM;;YAEN,OAAOJ,KAAAA;AACT,QAAA;QAEA,OAAOA,KAAAA;AACT,IAAA;AACF;;;;"}
|
|
@@ -46,7 +46,7 @@ const parseDateTimeOrTimestamp = (value)=>{
|
|
|
46
46
|
return milliUnixDate;
|
|
47
47
|
}
|
|
48
48
|
throw new invalidDatetime(`Invalid format, expected a timestamp or an ISO date`);
|
|
49
|
-
} catch
|
|
49
|
+
} catch {
|
|
50
50
|
throw new invalidDatetime(`Invalid format, expected a timestamp or an ISO date`);
|
|
51
51
|
}
|
|
52
52
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parsers.js","sources":["../../../src/fields/shared/parsers.ts"],"sourcesContent":["import { padCharsEnd, isString, toString } from 'lodash/fp';\nimport * as dateFns from 'date-fns';\n\nimport { InvalidDateTimeError, InvalidDateError, InvalidTimeError } from '../../errors';\n\nconst isDate = (value: unknown): value is Date => {\n return dateFns.isDate(value);\n};\n\nconst DATE_REGEX = /^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/;\nconst PARTIAL_DATE_REGEX = /^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])/g;\nconst TIME_REGEX = /^(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]{1,3})?$/;\n\nexport const parseDateTimeOrTimestamp = (value: unknown): Date => {\n if (isDate(value)) {\n return value;\n }\n\n try {\n const date = dateFns.parseISO(toString(value));\n if (dateFns.isValid(date)) {\n return date;\n }\n\n const milliUnixDate = dateFns.parse(toString(value), 'T', new Date());\n if (dateFns.isValid(milliUnixDate)) {\n return milliUnixDate;\n }\n\n throw new InvalidDateTimeError(`Invalid format, expected a timestamp or an ISO date`);\n } catch
|
|
1
|
+
{"version":3,"file":"parsers.js","sources":["../../../src/fields/shared/parsers.ts"],"sourcesContent":["import { padCharsEnd, isString, toString } from 'lodash/fp';\nimport * as dateFns from 'date-fns';\n\nimport { InvalidDateTimeError, InvalidDateError, InvalidTimeError } from '../../errors';\n\nconst isDate = (value: unknown): value is Date => {\n return dateFns.isDate(value);\n};\n\nconst DATE_REGEX = /^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/;\nconst PARTIAL_DATE_REGEX = /^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])/g;\nconst TIME_REGEX = /^(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]{1,3})?$/;\n\nexport const parseDateTimeOrTimestamp = (value: unknown): Date => {\n if (isDate(value)) {\n return value;\n }\n\n try {\n const date = dateFns.parseISO(toString(value));\n if (dateFns.isValid(date)) {\n return date;\n }\n\n const milliUnixDate = dateFns.parse(toString(value), 'T', new Date());\n if (dateFns.isValid(milliUnixDate)) {\n return milliUnixDate;\n }\n\n throw new InvalidDateTimeError(`Invalid format, expected a timestamp or an ISO date`);\n } catch {\n throw new InvalidDateTimeError(`Invalid format, expected a timestamp or an ISO date`);\n }\n};\n\nexport const parseDate = (value: unknown) => {\n if (isDate(value)) {\n return dateFns.format(value, 'yyyy-MM-dd');\n }\n\n const found = isString(value) ? value.match(PARTIAL_DATE_REGEX) || [] : [];\n const extractedValue = found[0];\n\n if (extractedValue && !DATE_REGEX.test(toString(value))) {\n // TODO V5: throw an error when format yyyy-MM-dd is not respected\n // throw new InvalidDateError(`Invalid format, expected yyyy-MM-dd`);\n process.emitWarning(\n `[deprecated] Using a date format other than YYYY-MM-DD will be removed in future versions. Date received: ${value}. Date stored: ${extractedValue}.`\n );\n }\n\n if (!extractedValue) {\n throw new InvalidDateError(`Invalid format, expected yyyy-MM-dd`);\n }\n\n const date = dateFns.parseISO(extractedValue);\n if (!dateFns.isValid(date)) {\n throw new InvalidDateError(`Invalid date`);\n }\n\n return extractedValue;\n};\n\nexport const parseTime = (value: unknown) => {\n if (isDate(value)) {\n return dateFns.format(value, 'HH:mm:ss.SSS');\n }\n\n if (typeof value !== 'string') {\n throw new InvalidTimeError(`Expected a string, got a ${typeof value}`);\n }\n\n const result = value.match(TIME_REGEX);\n\n if (result === null) {\n throw new InvalidTimeError('Invalid time format, expected HH:mm:ss.SSS');\n }\n\n const [, hours, minutes, seconds, fraction = '.000'] = result;\n const fractionPart = padCharsEnd('0', 3, fraction.slice(1));\n\n return `${hours}:${minutes}:${seconds}.${fractionPart}`;\n};\n"],"names":["isDate","value","dateFns","DATE_REGEX","PARTIAL_DATE_REGEX","TIME_REGEX","parseDateTimeOrTimestamp","date","parseISO","toString","isValid","milliUnixDate","parse","Date","InvalidDateTimeError","parseDate","format","found","isString","match","extractedValue","test","process","emitWarning","InvalidDateError","parseTime","InvalidTimeError","result","hours","minutes","seconds","fraction","fractionPart","padCharsEnd","slice"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAMA,SAAS,CAACC,KAAAA,GAAAA;IACd,OAAOC,kBAAAA,CAAQF,MAAM,CAACC,KAAAA,CAAAA;AACxB,CAAA;AAEA,MAAME,UAAAA,GAAa,kDAAA;AACnB,MAAMC,kBAAAA,GAAqB,kDAAA;AAC3B,MAAMC,UAAAA,GAAa,8DAAA;AAEZ,MAAMC,2BAA2B,CAACL,KAAAA,GAAAA;AACvC,IAAA,IAAID,OAAOC,KAAAA,CAAAA,EAAQ;QACjB,OAAOA,KAAAA;AACT,IAAA;IAEA,IAAI;AACF,QAAA,MAAMM,IAAAA,GAAOL,kBAAAA,CAAQM,QAAQ,CAACC,UAAAA,CAASR,KAAAA,CAAAA,CAAAA;QACvC,IAAIC,kBAAAA,CAAQQ,OAAO,CAACH,IAAAA,CAAAA,EAAO;YACzB,OAAOA,IAAAA;AACT,QAAA;AAEA,QAAA,MAAMI,gBAAgBT,kBAAAA,CAAQU,KAAK,CAACH,UAAAA,CAASR,KAAAA,CAAAA,EAAQ,KAAK,IAAIY,IAAAA,EAAAA,CAAAA;QAC9D,IAAIX,kBAAAA,CAAQQ,OAAO,CAACC,aAAAA,CAAAA,EAAgB;YAClC,OAAOA,aAAAA;AACT,QAAA;AAEA,QAAA,MAAM,IAAIG,eAAAA,CAAqB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AA;AAC/B,IAAA;IAEA,IAAI,OAAOA,UAAU,QAAA,EAAU;AAC7B,QAAA,MAAM,IAAIyB,WAAAA,CAAiB,CAAC,yBAAyB,EAAE,OAAOzB,KAAAA,CAAAA,CAAO,CAAA;AACvE,IAAA;IAEA,MAAM0B,MAAAA,GAAS1B,KAAAA,CAAMkB,KAAK,CAACd,UAAAA,CAAAA;AAE3B,IAAA,IAAIsB,WAAW,IAAA,EAAM;AACnB,QAAA,MAAM,IAAID,WAAAA,CAAiB,4CAAA,CAAA;AAC7B,IAAA;AAEA,IAAA,MAAM,GAAGE,KAAAA,EAAOC,OAAAA,EAASC,SAASC,QAAAA,GAAW,MAAM,CAAC,GAAGJ,MAAAA;AACvD,IAAA,MAAMK,eAAeC,aAAAA,CAAY,GAAA,EAAK,CAAA,EAAGF,QAAAA,CAASG,KAAK,CAAC,CAAA,CAAA,CAAA;IAExD,OAAO,CAAA,EAAGN,KAAAA,CAAM,CAAC,EAAEC,OAAAA,CAAQ,CAAC,EAAEC,OAAAA,CAAQ,CAAC,EAAEE,YAAAA,CAAAA,CAAc;AACzD;;;;;;"}
|
|
@@ -24,7 +24,7 @@ const parseDateTimeOrTimestamp = (value)=>{
|
|
|
24
24
|
return milliUnixDate;
|
|
25
25
|
}
|
|
26
26
|
throw new InvalidDateTimeError(`Invalid format, expected a timestamp or an ISO date`);
|
|
27
|
-
} catch
|
|
27
|
+
} catch {
|
|
28
28
|
throw new InvalidDateTimeError(`Invalid format, expected a timestamp or an ISO date`);
|
|
29
29
|
}
|
|
30
30
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parsers.mjs","sources":["../../../src/fields/shared/parsers.ts"],"sourcesContent":["import { padCharsEnd, isString, toString } from 'lodash/fp';\nimport * as dateFns from 'date-fns';\n\nimport { InvalidDateTimeError, InvalidDateError, InvalidTimeError } from '../../errors';\n\nconst isDate = (value: unknown): value is Date => {\n return dateFns.isDate(value);\n};\n\nconst DATE_REGEX = /^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/;\nconst PARTIAL_DATE_REGEX = /^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])/g;\nconst TIME_REGEX = /^(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]{1,3})?$/;\n\nexport const parseDateTimeOrTimestamp = (value: unknown): Date => {\n if (isDate(value)) {\n return value;\n }\n\n try {\n const date = dateFns.parseISO(toString(value));\n if (dateFns.isValid(date)) {\n return date;\n }\n\n const milliUnixDate = dateFns.parse(toString(value), 'T', new Date());\n if (dateFns.isValid(milliUnixDate)) {\n return milliUnixDate;\n }\n\n throw new InvalidDateTimeError(`Invalid format, expected a timestamp or an ISO date`);\n } catch
|
|
1
|
+
{"version":3,"file":"parsers.mjs","sources":["../../../src/fields/shared/parsers.ts"],"sourcesContent":["import { padCharsEnd, isString, toString } from 'lodash/fp';\nimport * as dateFns from 'date-fns';\n\nimport { InvalidDateTimeError, InvalidDateError, InvalidTimeError } from '../../errors';\n\nconst isDate = (value: unknown): value is Date => {\n return dateFns.isDate(value);\n};\n\nconst DATE_REGEX = /^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/;\nconst PARTIAL_DATE_REGEX = /^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])/g;\nconst TIME_REGEX = /^(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]{1,3})?$/;\n\nexport const parseDateTimeOrTimestamp = (value: unknown): Date => {\n if (isDate(value)) {\n return value;\n }\n\n try {\n const date = dateFns.parseISO(toString(value));\n if (dateFns.isValid(date)) {\n return date;\n }\n\n const milliUnixDate = dateFns.parse(toString(value), 'T', new Date());\n if (dateFns.isValid(milliUnixDate)) {\n return milliUnixDate;\n }\n\n throw new InvalidDateTimeError(`Invalid format, expected a timestamp or an ISO date`);\n } catch {\n throw new InvalidDateTimeError(`Invalid format, expected a timestamp or an ISO date`);\n }\n};\n\nexport const parseDate = (value: unknown) => {\n if (isDate(value)) {\n return dateFns.format(value, 'yyyy-MM-dd');\n }\n\n const found = isString(value) ? value.match(PARTIAL_DATE_REGEX) || [] : [];\n const extractedValue = found[0];\n\n if (extractedValue && !DATE_REGEX.test(toString(value))) {\n // TODO V5: throw an error when format yyyy-MM-dd is not respected\n // throw new InvalidDateError(`Invalid format, expected yyyy-MM-dd`);\n process.emitWarning(\n `[deprecated] Using a date format other than YYYY-MM-DD will be removed in future versions. Date received: ${value}. Date stored: ${extractedValue}.`\n );\n }\n\n if (!extractedValue) {\n throw new InvalidDateError(`Invalid format, expected yyyy-MM-dd`);\n }\n\n const date = dateFns.parseISO(extractedValue);\n if (!dateFns.isValid(date)) {\n throw new InvalidDateError(`Invalid date`);\n }\n\n return extractedValue;\n};\n\nexport const parseTime = (value: unknown) => {\n if (isDate(value)) {\n return dateFns.format(value, 'HH:mm:ss.SSS');\n }\n\n if (typeof value !== 'string') {\n throw new InvalidTimeError(`Expected a string, got a ${typeof value}`);\n }\n\n const result = value.match(TIME_REGEX);\n\n if (result === null) {\n throw new InvalidTimeError('Invalid time format, expected HH:mm:ss.SSS');\n }\n\n const [, hours, minutes, seconds, fraction = '.000'] = result;\n const fractionPart = padCharsEnd('0', 3, fraction.slice(1));\n\n return `${hours}:${minutes}:${seconds}.${fractionPart}`;\n};\n"],"names":["isDate","value","dateFns","DATE_REGEX","PARTIAL_DATE_REGEX","TIME_REGEX","parseDateTimeOrTimestamp","date","parseISO","toString","isValid","milliUnixDate","parse","Date","InvalidDateTimeError","parseDate","format","found","isString","match","extractedValue","test","process","emitWarning","InvalidDateError","parseTime","InvalidTimeError","result","hours","minutes","seconds","fraction","fractionPart","padCharsEnd","slice"],"mappings":";;;;;;AAKA,MAAMA,SAAS,CAACC,KAAAA,GAAAA;IACd,OAAOC,OAAAA,CAAQF,MAAM,CAACC,KAAAA,CAAAA;AACxB,CAAA;AAEA,MAAME,UAAAA,GAAa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GN,KAAAA,CAAM,CAAC,EAAEC,OAAAA,CAAQ,CAAC,EAAEC,OAAAA,CAAQ,CAAC,EAAEE,YAAAA,CAAAA,CAAc;AACzD;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timestamp.d.ts","sourceRoot":"","sources":["../../src/fields/timestamp.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"timestamp.d.ts","sourceRoot":"","sources":["../../src/fields/timestamp.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,SAAS,CAAC;AAE5B,MAAM,CAAC,OAAO,OAAO,cAAe,SAAQ,KAAK;IAC/C,IAAI,CAAC,KAAK,EAAE,OAAO;IAInB,MAAM,CAAC,KAAK,EAAE,OAAO;CAOtB"}
|