@dazejs/framework
Version:
Daze.js - A powerful web framework for Node.js
78 lines • 3.18 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HasOne = void 0;
const pluralize_1 = __importDefault(require("pluralize"));
const has_relations_abstract_1 = require("./has-relations.abstract");
class HasOne 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 record = await query
.getBuilder()
.where(foreignKey, '=', resultRepos.getAttribute(localKey))
.first();
if (record) {
const repos = await this.model.resultToRepository(model, record);
resultRepos.setAttribute(currentRelation, repos);
}
}
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) {
map.set(record[foreignKey], record);
}
for (const item of resultReposes) {
const record = map.get(item.getAttribute(localKey));
if (record) {
item.setAttribute(currentRelation, await this.model.resultToRepository(model, record, true));
}
}
}
}
}
exports.HasOne = HasOne;
//# sourceMappingURL=has-one.js.map