@webiny/api-headless-cms-ddb-es
Version:
DynamoDB and Elasticsearch storage operations plugin for Headless CMS API.
108 lines (106 loc) • 3.09 kB
JavaScript
import WebinyError from "@webiny/error";
import { DataLoaderCache } from "./dataLoader/DataLoaderCache.js";
import { getDataLoaderFactory } from "./dataLoader/index.js";
import { parseIdentifier } from "@webiny/utils";
export class DataLoadersHandler {
cache = new DataLoaderCache();
constructor(params) {
this.entity = params.entity;
}
async getAllEntryRevisions(params) {
const ids = params.ids.map(id => {
const {
id: entryId
} = parseIdentifier(id);
return entryId;
});
return await this.loadMany("getAllEntryRevisions", params, ids);
}
async getRevisionById(params) {
return await this.loadMany("getRevisionById", params, params.ids);
}
async getPublishedRevisionByEntryId(params) {
const ids = params.ids.map(id => {
const {
id: entryId
} = parseIdentifier(id);
return entryId;
});
return await this.loadMany("getPublishedRevisionByEntryId", params, ids);
}
async getLatestRevisionByEntryId(params) {
const ids = params.ids.map(id => {
const {
id: entryId
} = parseIdentifier(id);
return entryId;
});
return await this.loadMany("getLatestRevisionByEntryId", params, ids);
}
/**
* TODO @ts-refactor
* Maybe pass on the generics to DataLoader definition?
*/
getLoader(name, params) {
const {
model
} = params;
const cacheParams = {
tenant: model.tenant,
modelId: model.modelId,
name
};
let loader = this.cache.getDataLoader(cacheParams);
if (loader) {
return loader;
}
const factory = getDataLoaderFactory(name);
loader = factory({
entity: this.entity,
tenant: model.tenant,
modelId: model.modelId
});
this.cache.setDataLoader(cacheParams, loader);
return loader;
}
async loadMany(loader, params, ids) {
let results = [];
try {
results = await this.getLoader(loader, params).loadMany(ids);
if (Array.isArray(results) === true) {
return results.reduce((acc, res) => {
if (Array.isArray(res) === false) {
if (res && res.message) {
throw new WebinyError(res.message, res.code, {
...res,
data: JSON.stringify(res.data || {})
});
}
throw new WebinyError("Result from the data loader must be an array of arrays which contain requested items.", "DATA_LOADER_RESULTS_ERROR", {
...params,
loader
});
}
acc.push(...res);
return acc;
}, []);
}
} catch (ex) {
throw new WebinyError(ex.message || "Data loader error.", ex.code || "DATA_LOADER_ERROR", {
error: ex,
...params,
loader,
ids
});
}
throw new WebinyError(`Data loader did not return array of items or empty array.`, "INVALID_DATA_LOADER_RESULT", {
loader,
ids,
results
});
}
clearAll(params) {
this.cache.clearAll(params?.model);
}
}
//# sourceMappingURL=dataLoaders.js.map