@webiny/api-headless-cms-ddb-es
Version:
DynamoDB and Elasticsearch storage operations plugin for Headless CMS API.
142 lines (141 loc) • 3.14 kB
JavaScript
import WebinyError from "@webiny/error";
import { sortItems } from "@webiny/db-dynamodb";
import { FilterUtil } from "@webiny/db-dynamodb/exports/api/db.js";
const createPartitionKey = params => {
const {
tenant
} = params;
return `T
};
const createSortKeys = params => {
const {
id
} = params;
return id;
};
const createKeys = params => {
return {
PK: createPartitionKey(params),
SK: createSortKeys(params),
GSI_TENANT: params.tenant
};
};
const createType = () => {
return "cms.group";
};
export const createGroupsStorageOperations = params => {
const {
entity,
container
} = params;
const filterUtil = container.resolve(FilterUtil);
const create = async params => {
const {
group
} = params;
const keys = createKeys(group);
try {
await entity.put({
data: group,
TYPE: createType(),
...keys
});
} catch (ex) {
throw new WebinyError(ex.message || "Could not create group.", ex.code || "CREATE_GROUP_ERROR", {
error: ex,
group,
keys
});
}
};
const update = async params => {
const {
group
} = params;
const keys = createKeys(group);
try {
await entity.put({
data: group,
TYPE: createType(),
...keys
});
} catch (ex) {
throw new WebinyError(ex.message || "Could not update group.", ex.code || "UPDATE_GROUP_ERROR", {
error: ex,
group,
keys
});
}
};
const deleteGroup = async params => {
const {
group
} = params;
const keys = createKeys(group);
try {
await entity.delete(keys);
} catch (ex) {
throw new WebinyError(ex.message || "Could not delete group.", ex.code || "DELETE_GROUP_ERROR", {
error: ex,
group,
keys
});
}
};
const get = async params => {
const keys = createKeys(params);
try {
const result = await entity.get(keys);
return result ? result.data : null;
} catch (ex) {
throw new WebinyError(ex.message || "Could not get group.", ex.code || "GET_GROUP_ERROR", {
error: ex,
...params,
keys
});
}
};
const list = async params => {
const {
sort,
where
} = params;
let records = [];
try {
const ddbRecords = await entity.queryAll({
partitionKey: createPartitionKey(where),
options: {
gte: " "
}
});
records = ddbRecords.map(item => item.data);
} catch (ex) {
throw new WebinyError(ex.message || "Could not list groups.", ex.code || "LIST_GROUP_ERROR", {
error: ex,
...params,
sort,
where
});
}
const filteredItems = filterUtil.filter({
items: records,
where,
fields: []
});
if (!sort || sort.length === 0) {
return filteredItems;
}
return sortItems({
items: filteredItems,
sort
});
};
return {
create,
update,
delete: deleteGroup,
get,
list
};
};
//# sourceMappingURL=index.js.map