UNPKG

@decaf-ts/core

Version:

Core persistence module for the decaf framework

91 lines 4.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.prepared = prepared; exports.query = query; const MethodQueryBuilder_1 = require("./MethodQueryBuilder.cjs"); const errors_1 = require("./errors.cjs"); const decoration_1 = require("@decaf-ts/decoration"); const constants_1 = require("./../persistence/constants.cjs"); function prepared() { function prepared() { return function prepared(obj, prop, descriptor) { return (0, decoration_1.apply)((0, decoration_1.methodMetadata)(decoration_1.Metadata.key(constants_1.PersistenceKeys.STATEMENT, prop), true))(obj, prop, descriptor); }; } return decoration_1.Decoration.for(constants_1.PersistenceKeys.STATEMENT) .define({ decorator: prepared, args: [], }) .apply(); } function query(options = {}) { function query(options) { return function query(obj, prop, descriptor) { function innerQuery(options) { return function innerQuery(obj, propertyKey, descriptor) { descriptor.value = new Proxy(descriptor.value, { apply(target, thisArg, args) { const { select, where, groupBy, orderBy, limit, offset } = MethodQueryBuilder_1.MethodQueryBuilder.build(target.name, ...args); let stmt = thisArg.select(select); if (where) stmt = stmt.where(where); // if (orderBy) stmt = stmt.orderBy(orderBy[0]); if (groupBy) { // group by not implemented yet /* stmt = stmt.groupBy(groupBy); */ } // allow limit and offset by default const { allowLimit, allowOffset, allowOrderBy, throws } = { allowLimit: true, allowOrderBy: true, allowOffset: true, throws: true, ...options, }; const params = [ // keep the order to ensure the expected behavior { key: "orderBy", value: (orderBy || [])[0], // orderBy only supports one sentence allowed: allowOrderBy, }, { key: "limit", value: limit, allowed: allowLimit }, { key: "offset", value: offset, allowed: allowOffset }, ]; for (const param of params) { if (param.value !== undefined) { if (!param.allowed && throws) { throw new errors_1.QueryError(`${param.key[0].toUpperCase() + param.key.slice(1)} is not allowed for this query`); } else if (param.allowed) { stmt = stmt[param.key](param.value); } } } return stmt.execute(); }, }); }; } const fields = MethodQueryBuilder_1.MethodQueryBuilder.getFieldsFromMethodName(prop); // const paramNames = descriptor.value // .toString() // .match(/\(([^)]*)\)/)?.[1] // .split(",") // .map((x) => x.trim()) // .filter(Boolean); return (0, decoration_1.apply)((0, decoration_1.methodMetadata)(decoration_1.Metadata.key(constants_1.PersistenceKeys.QUERY, prop), { ...options, fields, }), prepared(), innerQuery(options))(obj, prop, descriptor); }; } return decoration_1.Decoration.for(constants_1.PersistenceKeys.QUERY) .define({ decorator: query, args: [options], }) .apply(); } //# sourceMappingURL=decorators.js.map