dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
68 lines (67 loc) • 2.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MapSchema = void 0;
const index_js_1 = require("../../errors/index.js");
const checkSchemaProps_js_1 = require("../utils/checkSchemaProps.js");
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;
}
(0, checkSchemaProps_js_1.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 index_js_1.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);
}
}
exports.MapSchema = MapSchema;