@dazejs/framework
Version:
Daze.js - A powerful web framework for Node.js
80 lines • 3.27 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HasMany = void 0;
const pluralize_1 = __importDefault(require("pluralize"));
const has_relations_abstract_1 = require("./has-relations.abstract");
class HasMany 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.parent.getTable())}_${this.parent.getPrimaryKey()}`;
}
getDefaultLocalKey() {
return this.parent.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 records = await query
.getBuilder()
.where(foreignKey, '=', resultRepos.getAttribute(localKey))
.find();
if (records) {
resultRepos.setAttribute(currentRelation, await this.model.resultToRepositories(model, records));
}
}
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(localKey);
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(foreignKey, [...range])
.find();
const map = new Map();
for (const record of records) {
const pk = record[foreignKey];
const items = map.get(pk) || [];
items.push(record);
map.set(pk, items);
}
for (const repos of resultReposes) {
const items = map.get(repos.getAttribute(localKey));
if (items) {
repos.setAttribute(currentRelation, await this.model.resultToRepositories(model, records));
}
}
}
}
}
exports.HasMany = HasMany;
//# sourceMappingURL=has-many.js.map