dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
64 lines (63 loc) • 2.69 kB
JavaScript
import { DynamoDBToolboxError } from '../../errors/index.js';
import { checkSchemaProps } from '../utils/checkSchemaProps.js';
export class MapSchema {
constructor(attributes, props) {
this.type = 'map';
this.attributes = attributes;
this.props = props;
this.keyAttributeNames = new Set();
this.savedAttributeNames = new Set();
this.requiredAttributeNames = {
always: new Set(),
atLeastOnce: new Set(),
never: new Set()
};
for (const [attributeName, attribute] of Object.entries(attributes)) {
const { key = false, required = 'atLeastOnce', savedAs = attributeName } = attribute.props;
this.savedAttributeNames.add(savedAs);
if (key) {
this.keyAttributeNames.add(attributeName);
}
this.requiredAttributeNames[required].add(attributeName);
}
}
get checked() {
return Object.isFrozen(this.props);
}
check(path) {
if (this.checked) {
return;
}
checkSchemaProps(this.props, path);
const attributesSavedAs = new Set();
const keyAttributeNames = new Set();
const requiredAttributeNames = {
always: new Set(),
atLeastOnce: new Set(),
never: new Set()
};
for (const [attributeName, attribute] of Object.entries(this.attributes)) {
const { savedAs: attributeSavedAs = attributeName, key: attributeKey, required: attributeRequired = 'atLeastOnce' } = attribute.props;
if (attributesSavedAs.has(attributeSavedAs)) {
throw new DynamoDBToolboxError('schema.map.duplicateSavedAs', {
message: `Invalid map attributes${path !== undefined ? ` at path '${path}'` : ''}: More than two attributes are saved as '${attributeSavedAs}'.`,
path,
payload: { savedAs: attributeSavedAs }
});
}
attributesSavedAs.add(attributeSavedAs);
if (attributeKey !== undefined && attributeKey) {
keyAttributeNames.add(attributeName);
}
requiredAttributeNames[attributeRequired].add(attributeName);
}
for (const [attributeName, attribute] of Object.entries(this.attributes)) {
attribute.check([path, attributeName].filter(Boolean).join('.'));
}
Object.freeze(this.props);
Object.freeze(this.attributes);
Object.freeze(this.savedAttributeNames);
Object.freeze(this.keyAttributeNames);
Object.freeze(this.requiredAttributeNames);
}
}