@decaf-ts/db-decorators
Version:
Agnostic database decorators and repository
66 lines (65 loc) • 2.69 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.findPrimaryKey = findPrimaryKey;
exports.findModelId = findModelId;
const constants_1 = require("../model/constants.cjs");
const utils_1 = require("../repository/utils.cjs");
const decorator_validation_1 = require("@decaf-ts/decorator-validation");
const errors_1 = require("../repository/errors.cjs");
/**
* @summary Returns the primary key attribute for a {@link Model}
* @description searches in all the properties in the object for an {@link id} decorated property
*
* @param {Model} model
*
* @throws {InternalError} if no property or more than one properties are {@link id} decorated
* or no value is set in that property
*
* @function findPrimaryKey
*
* @category managers
*/
function findPrimaryKey(model) {
const decorators = (0, utils_1.getAllPropertyDecoratorsRecursive)(model, undefined, constants_1.DBKeys.REFLECT + constants_1.DBKeys.ID);
const idDecorators = Object.entries(decorators).reduce((accum, [prop, decs]) => {
const filtered = decs.filter((d) => d.key !== decorator_validation_1.ModelKeys.TYPE);
if (filtered && filtered.length) {
accum[prop] = accum[prop] || [];
accum[prop].push(...filtered);
}
return accum;
}, {});
if (!idDecorators || !Object.keys(idDecorators).length)
throw new errors_1.InternalError("Could not find ID decorated Property");
if (Object.keys(idDecorators).length > 1)
throw new errors_1.InternalError((0, decorator_validation_1.sf)(Object.keys(idDecorators).join(", ")));
const idProp = Object.keys(idDecorators)[0];
if (!idProp)
throw new errors_1.InternalError("Could not find ID decorated Property");
return {
id: idProp,
props: idDecorators[idProp][0].props,
};
}
/**
* @summary Returns the primary key value for a {@link Model}
* @description searches in all the properties in the object for an {@link pk} decorated property
*
* @param {Model} model
* @param {boolean} [returnEmpty]
* @return {string} primary key
*
* @throws {InternalError} if no property or more than one properties are {@link pk} decorated
* @throws {NotFoundError} returnEmpty is false and no value is set on the {@link pk} decorated property
*
* @function findModelID
*
* @category managers
*/
function findModelId(model, returnEmpty = false) {
const idProp = findPrimaryKey(model).id;
const modelId = model[idProp];
if (!modelId && !returnEmpty)
throw new errors_1.InternalError((0, decorator_validation_1.sf)("No value for the Id is defined under the property {0}", idProp));
return modelId;
}