UNPKG

dynamodb-toolbox

Version:

Lightweight and type-safe query builder for DynamoDB and TypeScript.

60 lines (59 loc) 3.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildEntitySchema = void 0; const get_js_1 = require("../../../entity/actions/update/symbols/get.js"); const index_js_1 = require("../../../errors/index.js"); const schema_js_1 = require("../../../schema/item/schema.js"); const schema_js_2 = require("../../../schema/string/schema.js"); const utils_js_1 = require("./utils.js"); const buildEntitySchema = ({ schema, table, entityName, entityAttribute, timestamps }) => { const internalAttributes = {}; if ((0, utils_js_1.isEntityAttrEnabled)(entityAttribute)) { const entityAttrName = (0, utils_js_1.getEntityAttrOptionValue)(entityAttribute, 'name'); const entityAttr = new schema_js_2.StringSchema({ hidden: (0, utils_js_1.getEntityAttrOptionValue)(entityAttribute, 'hidden'), enum: [entityName], putDefault: entityName, updateDefault: () => (0, get_js_1.$get)(entityAttrName, entityName), savedAs: table.entityAttributeSavedAs }); internalAttributes[entityAttrName] = entityAttr; } if ((0, utils_js_1.isTimestampEnabled)(timestamps, 'created')) { const createdName = (0, utils_js_1.getTimestampOptionValue)(timestamps, 'created', 'name'); const createdAttribute = new schema_js_2.StringSchema({ hidden: (0, utils_js_1.getTimestampOptionValue)(timestamps, 'created', 'hidden'), savedAs: (0, utils_js_1.getTimestampOptionValue)(timestamps, 'created', 'savedAs'), putDefault: () => new Date().toISOString(), updateDefault: () => (0, get_js_1.$get)(createdName, new Date().toISOString()) }); internalAttributes[createdName] = createdAttribute; } if ((0, utils_js_1.isTimestampEnabled)(timestamps, 'modified')) { const modifiedName = (0, utils_js_1.getTimestampOptionValue)(timestamps, 'modified', 'name'); const modifiedAttribute = new schema_js_2.StringSchema({ hidden: (0, utils_js_1.getTimestampOptionValue)(timestamps, 'modified', 'hidden'), savedAs: (0, utils_js_1.getTimestampOptionValue)(timestamps, 'modified', 'savedAs'), putDefault: () => new Date().toISOString(), updateDefault: () => new Date().toISOString() }); internalAttributes[modifiedName] = modifiedAttribute; } for (const [attributeName, attribute] of Object.entries(internalAttributes)) { if (attributeName in schema.attributes) { throw new index_js_1.DynamoDBToolboxError('entity.reservedAttributeName', { message: `'${attributeName}' is a reserved attribute name.`, path: attributeName }); } const { savedAs: attributeSavedAs } = attribute.props; if (attributeSavedAs !== undefined && schema.savedAttributeNames.has(attributeSavedAs)) { throw new index_js_1.DynamoDBToolboxError('entity.reservedAttributeSavedAs', { message: `'${attributeSavedAs}' is a reserved attribute alias (savedAs).`, path: attributeName }); } } return new schema_js_1.ItemSchema({ ...schema.attributes, ...internalAttributes }); }; exports.buildEntitySchema = buildEntitySchema;