@webiny/api-headless-cms-ddb-es
Version:
DynamoDB and Elasticsearch storage operations plugin for Headless CMS API.
103 lines (102 loc) • 2.79 kB
JavaScript
import { createSort, OpenSearchFieldPlugin } from "@webiny/api-opensearch";
import { hasKeyword } from "./keyword.js";
import { createFieldPathFactory } from "./filtering/path.js";
import { NoValueContainer } from "../../../values/NoValueContainer.js";
const matchField = input => {
const valuesMatch = input.match(/^values_([a-zA-Z-0-9_]+)_(ASC|DESC)$/);
if (valuesMatch) {
const [, fieldId, order] = valuesMatch;
return {
fieldId,
isValues: true,
order: order
};
}
const nonValues = input.match(/^([a-zA-Z-0-9_]+)_(ASC|DESC)$/);
if (!nonValues) {
return null;
}
const [, fieldId, order] = nonValues;
return {
fieldId,
isValues: false,
order: order
};
};
export const createElasticsearchSort = params => {
const {
sort,
modelFields,
valueSearchRegistry
} = params;
if (!sort || sort.length === 0) {
return [{
["id.keyword"]: {
order: "asc"
}
}];
}
const createFieldPath = createFieldPathFactory({
valueSearchRegistry
});
const fieldIdToStorageIdIdMap = {};
const sortPlugins = Object.values(modelFields).reduce((plugins, field) => {
/**
* We do not support sorting by nested fields.
*/
const isValues = field.parents.length === 1 && field.parents[0].fieldId === "values";
if (field.parents.length > 0 && !isValues) {
return plugins;
}
const fieldId = field.field.fieldId;
const fieldIdPath = isValues ? `values.${fieldId}` : fieldId;
fieldIdToStorageIdIdMap[fieldIdPath] = fieldIdPath;
const {
path
} = createFieldPath({
key: field.field.storageId,
field,
value: NoValueContainer.create(),
keyword: false,
originalValue: NoValueContainer.create()
});
/**
* Plugins must be stored with fieldId as key because it is later used to find the sorting plugin.
*/
plugins[fieldIdPath] = new OpenSearchFieldPlugin({
unmappedType: field.unmappedType,
keyword: hasKeyword(field),
sortable: field.sortable,
searchable: field.searchable,
field: fieldId,
path
});
return plugins;
}, {
["*"]: new OpenSearchFieldPlugin({
field: OpenSearchFieldPlugin.ALL,
keyword: false
})
});
const transformedSort = sort.map(value => {
const matched = matchField(value);
if (!matched) {
return null;
}
const {
fieldId,
order,
isValues
} = matched;
const key = isValues ? `values.${fieldId}` : fieldId;
if (fieldIdToStorageIdIdMap[key]) {
return `${fieldIdToStorageIdIdMap[key]}_${order}`;
}
return value;
}).filter(Boolean);
return createSort({
fieldPlugins: sortPlugins,
sort: transformedSort
});
};
//# sourceMappingURL=sort.js.map