UNPKG

mvom

Version:

Multivalue Object Mapper

71 lines (64 loc) 2.41 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _lodash = require("lodash"); var _Document = _interopRequireDefault(require("../Document")); var _BaseSchemaType = _interopRequireDefault(require("./BaseSchemaType")); /** Embedded Schema Type */ class EmbeddedType extends _BaseSchemaType.default { /** An instance of Schema representing the the document structure of embedded object contents */ constructor(valueSchema) { super(); this.valueSchema = valueSchema; } /** * Cast to embedded data type * @throws {@link TypeError} Throws if a non-null/non-object is passed */ cast(value) { // convert value to a plain structure and then recast as embedded document const plainValue = value == null ? {} : JSON.parse(JSON.stringify(value)); if (!(0, _lodash.isPlainObject)(plainValue)) { throw new TypeError('Cast value must be an object'); } return _Document.default.createSubdocumentFromData(this.valueSchema, plainValue); } /** Get value from mv data */ get(record) { const embeddedDocument = _Document.default.createSubdocumentFromRecord(this.valueSchema, record); return embeddedDocument; } /** Set specified embedded document value into mv record */ set(originalRecord, setValue) { const record = (0, _lodash.cloneDeep)(originalRecord); const subrecord = setValue.transformDocumentToRecord(); subrecord.forEach((value, arrayPos) => { if (typeof value !== 'undefined') { (0, _lodash.set)(record, [arrayPos], value); } }); return record; } /** Validate the embedded document */ validate(document) { // - validation against the embedded document will return a single object with 0 to n keys - only those with keys indicate errors; return document.validate(); } /** Create an array of foreign key definitions that will be validated before save */ transformForeignKeyDefinitionsToDb(document) { const documentForeignKeyDefinitions = document.buildForeignKeyDefinitions(); return documentForeignKeyDefinitions.flatMap(({ filename, entityName, entityIds }) => entityIds.map(entityId => ({ filename, entityName, entityId }))); } } var _default = exports.default = EmbeddedType;