UNPKG

dynamodb-toolbox

Version:

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

56 lines (55 loc) 2.96 kB
import { $get } from '../../../entity/actions/update/symbols/get.js'; import { DynamoDBToolboxError } from '../../../errors/index.js'; import { ItemSchema } from '../../../schema/item/schema.js'; import { StringSchema } from '../../../schema/string/schema.js'; import { getEntityAttrOptionValue, getTimestampOptionValue, isEntityAttrEnabled, isTimestampEnabled } from './utils.js'; export const buildEntitySchema = ({ schema, table, entityName, entityAttribute, timestamps }) => { const internalAttributes = {}; if (isEntityAttrEnabled(entityAttribute)) { const entityAttrName = getEntityAttrOptionValue(entityAttribute, 'name'); const entityAttr = new StringSchema({ hidden: getEntityAttrOptionValue(entityAttribute, 'hidden'), enum: [entityName], putDefault: entityName, updateDefault: () => $get(entityAttrName, entityName), savedAs: table.entityAttributeSavedAs }); internalAttributes[entityAttrName] = entityAttr; } if (isTimestampEnabled(timestamps, 'created')) { const createdName = getTimestampOptionValue(timestamps, 'created', 'name'); const createdAttribute = new StringSchema({ hidden: getTimestampOptionValue(timestamps, 'created', 'hidden'), savedAs: getTimestampOptionValue(timestamps, 'created', 'savedAs'), putDefault: () => new Date().toISOString(), updateDefault: () => $get(createdName, new Date().toISOString()) }); internalAttributes[createdName] = createdAttribute; } if (isTimestampEnabled(timestamps, 'modified')) { const modifiedName = getTimestampOptionValue(timestamps, 'modified', 'name'); const modifiedAttribute = new StringSchema({ hidden: getTimestampOptionValue(timestamps, 'modified', 'hidden'), savedAs: 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 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 DynamoDBToolboxError('entity.reservedAttributeSavedAs', { message: `'${attributeSavedAs}' is a reserved attribute alias (savedAs).`, path: attributeName }); } } return new ItemSchema({ ...schema.attributes, ...internalAttributes }); };