@grouparoo/core
Version:
The Grouparoo Core
45 lines (44 loc) • 1.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourcesCache = void 0;
const modelCache_1 = require("../modelCache");
const Source_1 = require("../../models/Source");
const Option_1 = require("../../models/Option");
const Mapping_1 = require("../../models/Mapping");
async function findAllWithCache(modelId, state) {
const now = Date.now();
if (this.expires > now && this.instances.length > 0) {
return modelId
? this.instances.filter((s) => (s === null || s === void 0 ? void 0 : s.modelId) === modelId && (!state || s.state === state))
: this.instances.filter((s) => !state || s.state === state);
}
else {
this.instances = await Source_1.Source.unscoped().findAll({
include: this.include(),
});
this.expires = now + this.TTL;
return modelId
? this.instances.filter((s) => (s === null || s === void 0 ? void 0 : s.modelId) === modelId && (!state || s.state === state))
: this.instances.filter((s) => !state || s.state === state);
}
}
async function findOneWithCache(value, modelId, state, lookupKey = "id") {
const instances = await this.findAllWithCache(modelId);
let instance = instances.find((i) => i[lookupKey] === value);
if (!instance) {
const where = { [lookupKey]: value };
if (state)
where.state = state;
instance = await Source_1.Source.unscoped().findOne({
where,
include: this.include(),
});
if (instance)
this.invalidate();
}
return instance;
}
exports.SourcesCache = new modelCache_1.ModelCache(findAllWithCache, findOneWithCache, () => [
{ model: Option_1.Option, required: false },
{ model: Mapping_1.Mapping, required: false },
]);