UNPKG

@dazejs/framework

Version:

Daze.js - A powerful web framework for Node.js

80 lines 3.21 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BelongsTo = void 0; const pluralize_1 = __importDefault(require("pluralize")); const has_relations_abstract_1 = require("./has-relations.abstract"); class BelongsTo extends has_relations_abstract_1.HasRelations { constructor(parent, model, foreignKey, localKey) { super(); this.parent = parent; this.model = model; this.foreignKey = foreignKey !== null && foreignKey !== void 0 ? foreignKey : this.getDefaultForeignKey(); this.localKey = localKey !== null && localKey !== void 0 ? localKey : this.getDefaultLocalKey(); } getDefaultForeignKey() { return `${pluralize_1.default.singular(this.model.getTable())}_${this.model.getPrimaryKey()}`; } getDefaultLocalKey() { return this.model.getPrimaryKey(); } async eagerly(resultRepos, relation, queryCallback) { const foreignKey = this.foreignKey; const localKey = this.localKey; const model = this.model.createRepository(); const [currentRelation, ...restRelation] = relation.split('.'); if (restRelation.length) { model.with(restRelation.join('.')); } const query = model.createQueryBuilder(); if (queryCallback) queryCallback(query); const data = await query .getBuilder() .where(localKey, '=', resultRepos.getAttribute(foreignKey)) .first(); if (data) { resultRepos.setAttribute(currentRelation, await this.model.resultToRepository(model, data)); } } async eagerlyMap(resultReposes, relation, queryCallback) { const foreignKey = this.foreignKey; const localKey = this.localKey; const range = new Set(); for (const repos of resultReposes) { const id = repos.getAttribute(foreignKey); if (id) { range.add(id); } } if (range.size > 0) { const model = this.model.createRepository(); const [currentRelation, ...restRelation] = relation.split('.'); if (restRelation.length) { model.with(restRelation.join('.')); } const query = model.createQueryBuilder(); if (queryCallback) queryCallback(query); const records = await query .getBuilder() .whereIn(localKey, [...range]) .find(); const map = new Map(); for (const record of records) { const pk = record[localKey]; map.set(pk, record); } for (const repos of resultReposes) { const item = map.get(repos.getAttribute(foreignKey)); if (item) { repos.setAttribute(currentRelation, await this.model.resultToRepository(model, item)); } } } } } exports.BelongsTo = BelongsTo; //# sourceMappingURL=belongs-to.js.map