UNPKG

@decaf-ts/db-decorators

Version:

Agnostic database decorators and repository

89 lines 3.16 kB
import { BulkCrudOperationKeys, ModelOperations, OperationKeys, } from "./../operations/constants.js"; import { InternalError } from "./errors.js"; import { getHandlersDecorators, groupDecorators, sortDecorators, } from "./../operations/decorators.js"; import { Metadata } from "@decaf-ts/decoration"; export function reduceErrorsToPrint(errors) { return errors.reduce((accum, e, i) => { if (e) accum = typeof accum === "string" ? accum + `\n - ${i}: ${e.toString()}` : ` - ${i}: ${e.toString()}`; return accum; }, undefined); } /** * * @param {IRepository<T>} repo * @param context * @param {T} model * @param operation * @param prefix * * @param oldModel * @function enforceDBPropertyDecoratorsAsync * * @memberOf db-decorators.utils */ export async function enforceDBDecorators(repo, context, model, operation, prefix, oldModel) { const decorators = getDbDecorators(model, operation, prefix); if (!decorators) return; const hanlersDecorators = getHandlersDecorators(model, decorators, prefix); const groupedDecorators = groupDecorators(hanlersDecorators); const sortedDecorators = sortDecorators(groupedDecorators); for (const dec of sortedDecorators) { const args = [ context, dec.data.length > 1 ? dec.data : dec.data[0], dec.prop.length > 1 ? dec.prop : dec.prop[0], model, ]; if ([OperationKeys.UPDATE, BulkCrudOperationKeys.UPDATE_ALL].includes(operation)) { if (!oldModel) throw new InternalError("Missing old model for update operation"); args.push(oldModel); } try { await dec.handler.apply(repo, args); } catch (e) { const msg = `Failed to execute handler ${dec.handler.name} for ${dec.prop} on ${model.constructor.name} due to error: ${e}`; if (context.get("breakOnHandlerError")) throw new InternalError(msg); context.logger.for(enforceDBDecorators).error(msg); } } } /** * Specific for DB Decorators * @param {T} model * @param {string} operation CRUD {@link OperationKeys} * @param {string} [extraPrefix] * * @function getDbPropertyDecorators * * @memberOf db-decorators.utils */ export function getDbDecorators(model, operation, extraPrefix) { const prefix = extraPrefix?.replace(/[.]$/, ""); const decorators = Metadata.get(model.constructor, ModelOperations.OPERATIONS); if (!decorators) return; return Object.keys(decorators).reduce((accum, decorator) => { const obj = prefix ? decorators[decorator][prefix] || {} : decorators[decorator]; const dec = Object.keys(obj).filter((d) => d === operation); const decs = []; for (const d of dec) decs.push({ key: d, props: obj[d] }); if (decs && decs.length) { if (!accum) accum = {}; accum[decorator] = decs; } return accum; }, undefined); } //# sourceMappingURL=utils.js.map