won-dto
Version:
Won DTO For WonCore
85 lines • 3.02 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModelHook = exports.ModelLoader = void 0;
const dataloader_1 = __importDefault(require("dataloader"));
const mongoose_unique_validator_1 = __importDefault(require("mongoose-unique-validator"));
const lru_map_1 = require("lru_map");
const rxjs_1 = require("rxjs");
function ModelLoader(model, modelHook, cache = true) {
model.schema.plugin(mongoose_unique_validator_1.default, { message: "{VALUE} đã tồn tại." });
let loader;
const batchFunction = async (ids) => {
const list = await model.find({ _id: { $in: ids } });
const listByKey = {};
list.forEach((item) => {
listByKey[item._id.toString()] = item;
});
return ids.map((id) => listByKey[id] || null);
};
loader = new dataloader_1.default(batchFunction, { cacheMap: new lru_map_1.LRUMap(100), cache } // Giới hạn chỉ cache 100 item sử dụng nhiêu nhất.
);
if (modelHook) {
// modelHook.onFindOne.subscribe((doc: any) => loader.prime(doc._id.toString(), doc));
modelHook.onDeleted.subscribe((doc) => loader.clear(doc._id.toString()));
}
return loader;
}
exports.ModelLoader = ModelLoader;
class ModelHook {
constructor(schema) {
this.onSaved = new rxjs_1.Subject();
this.onUpdated = new rxjs_1.Subject();
this.onDeleted = new rxjs_1.Subject();
this.onFindOne = new rxjs_1.Subject();
schema.post("findOne", (doc, next) => {
if (doc)
this.onFindOne.next(doc);
next(null);
});
schema.post("save", (doc, next) => {
if (doc)
this.onSaved.next(doc);
next();
});
schema.post("updateMany", (doc, next) => {
if (doc)
this.onUpdated.next(doc);
next();
});
schema.post("updateOne", (doc, next) => {
if (doc)
this.onUpdated.next(doc);
next();
});
schema.post("findOneAndUpdate", (doc, next) => {
if (doc)
this.onUpdated.next(doc);
next();
});
schema.post("deleteOne", (doc, next) => {
if (doc)
this.onDeleted.next(doc);
next();
});
schema.post("deleteMany", (doc, next) => {
if (doc)
this.onDeleted.next(doc);
next();
});
schema.post("findOneAndDelete", (doc, next) => {
if (doc)
this.onDeleted.next(doc);
next();
});
schema.post("findOneAndRemove", (doc, next) => {
if (doc)
this.onDeleted.next(doc);
next();
});
}
}
exports.ModelHook = ModelHook;
//# sourceMappingURL=baseModel.js.map