dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
86 lines (85 loc) • 3.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.findSubSchemas = exports.Finder = void 0;
const index_js_1 = require("../../../schema/actions/parse/index.js");
const parseStringPath_js_1 = require("../../../schema/actions/utils/parseStringPath.js");
const path_js_1 = require("../../../schema/actions/utils/path.js");
const schema_js_1 = require("../../../schema/any/schema.js");
const index_js_2 = require("../../../schema/index.js");
const isInteger_js_1 = require("../../../utils/validation/isInteger.js");
const subSchema_js_1 = require("./subSchema.js");
// TO IMPROVE: Type path as Path<SCHEMA> and return typed SubSchema
class Finder extends index_js_2.SchemaAction {
search(path) {
return (0, exports.findSubSchemas)(this.schema, (0, parseStringPath_js_1.parseStringPath)(path));
}
}
exports.Finder = Finder;
Finder.actionName = 'finder';
const findSubSchemas = (schema, path) => {
var _a;
const [pathHead, ...pathTail] = path;
if (pathHead === undefined) {
return [new subSchema_js_1.SubSchema({ schema, formattedPath: new path_js_1.Path(), transformedPath: new path_js_1.Path() })];
}
switch (schema.type) {
case 'any': {
return [
new subSchema_js_1.SubSchema({
schema: new schema_js_1.AnySchema({}),
formattedPath: path_js_1.Path.fromArray(path),
transformedPath: path_js_1.Path.fromArray(path)
})
];
}
case 'null':
case 'boolean':
case 'number':
case 'string':
case 'binary':
case 'set':
return [];
case 'record': {
const keyAttribute = schema.keys;
let parsedKey;
try {
parsedKey = new index_js_1.Parser(keyAttribute).parse(pathHead);
}
catch {
return [];
}
return (0, exports.findSubSchemas)(schema.elements, pathTail).map(({ schema, formattedPath, transformedPath }) => new subSchema_js_1.SubSchema({
schema,
formattedPath: formattedPath.prepend(pathHead),
transformedPath: transformedPath.prepend(parsedKey)
}));
}
case 'item':
case 'map': {
const childAttribute = schema.attributes[pathHead];
if (!childAttribute) {
return [];
}
const transformedLocalPath = (_a = childAttribute.props.savedAs) !== null && _a !== void 0 ? _a : pathHead;
return (0, exports.findSubSchemas)(childAttribute, pathTail).map(({ schema, formattedPath, transformedPath }) => new subSchema_js_1.SubSchema({
schema,
formattedPath: formattedPath.prepend(pathHead),
transformedPath: transformedPath.prepend(transformedLocalPath)
}));
}
case 'list': {
if (!(0, isInteger_js_1.isInteger)(pathHead)) {
return [];
}
return (0, exports.findSubSchemas)(schema.elements, pathTail).map(({ schema, formattedPath, transformedPath }) => new subSchema_js_1.SubSchema({
schema,
formattedPath: formattedPath.prepend(pathHead),
transformedPath: transformedPath.prepend(pathHead)
}));
}
case 'anyOf': {
return schema.elements.map(element => (0, exports.findSubSchemas)(element, path)).flat();
}
}
};
exports.findSubSchemas = findSubSchemas;