UNPKG

@cheetah.js/orm

Version:
90 lines (89 loc) 3.47 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValueProcessor = void 0; const value_object_1 = require("../common/value-object"); const base_entity_1 = require("../domain/base-entity"); const entities_1 = require("../domain/entities"); const utils_1 = require("../utils"); class ValueProcessor { static processForInsert(values, options) { const newValue = {}; for (const value in values) { const columnName = ValueProcessor.getColumnName(value, options); if (ValueProcessor.isValueObject(values[value])) { newValue[columnName] = values[value].getValue(); continue; } if (ValueProcessor.isBaseEntity(values[value])) { // @ts-ignore newValue[columnName] = values[value].id; continue; } newValue[columnName] = values[value]; } return newValue; } static processForUpdate(values, options) { const newValue = {}; for (const value in values) { const columnName = ValueProcessor.getColumnName(value, options); if (ValueProcessor.isValueObject(values[value])) { newValue[columnName] = values[value].getValue(); continue; } newValue[columnName] = values[value]; } return newValue; } static getColumnName(propertyKey, entity) { if (propertyKey.startsWith('$')) { return propertyKey; } const property = entity.properties[propertyKey]; const relation = entity.relations?.find(rel => rel.propertyKey === propertyKey); if (!property) { if (!relation) { throw new Error('Property not found'); } return relation.columnName || propertyKey; } return property.options.columnName || propertyKey; } static createInstance(values, entity, moment = undefined) { const entityStorage = entities_1.EntityStorage.getInstance(); const entityOptions = entityStorage.get(entity); const instance = new entity(); if (!entityOptions) { throw new Error('Entity not found'); } const property = Object.entries(entityOptions.properties); const relations = entityOptions.relations; property.forEach(([key, property]) => { if (property.options.onInsert && moment === 'insert') { instance[key] = property.options.onInsert(); } if (property.options.onUpdate && moment === 'update') { instance[key] = property.options.onUpdate(); } const columnName = property.options.columnName; if (columnName in values) { instance[key] = values[columnName]; } }); if (relations) { for (const relation of relations) { if (relation.relation === 'many-to-one') { instance[relation.propertyKey] = values[relation.columnName]; } } } return instance; } static isValueObject(value) { return (0, utils_1.extendsFrom)(value_object_1.ValueObject, value?.constructor?.prototype); } static isBaseEntity(value) { return value instanceof base_entity_1.BaseEntity; } } exports.ValueProcessor = ValueProcessor;