@opra/elastic
Version:
Opra Elastic Search adapter package
66 lines (65 loc) • 2.44 kB
JavaScript
import { ComplexType, parseFieldsProjection, } from '@opra/common';
export default function prepareProjection(dataType, projection, scope) {
const out = {};
const includes = [];
const excludes = [];
const projection_ = typeof projection === 'string' || Array.isArray(projection)
? parseFieldsProjection(projection)
: projection;
prepare(dataType, includes, excludes, '', projection_, scope);
if (includes.length)
out.includes = includes;
if (excludes.length)
out.excludes = excludes;
return includes.length || excludes.length ? out : undefined;
}
function getNeedIncludes(projection) {
return !!(projection && Object.values(projection).find(p => !p.sign));
}
export function prepare(dataType, includes, excludes, curPath, projection, scope) {
const needIncludes = getNeedIncludes(projection);
const projectionKeys = projection && Object.keys(projection);
const projectionKeysSet = new Set(projectionKeys);
let fieldName;
let fieldPath;
let field;
let k;
/** Add fields from data type */
for (field of dataType.fields(scope)) {
fieldName = field.name;
fieldPath = curPath + (curPath ? '.' : '') + fieldName;
k = fieldName.toLowerCase();
projectionKeysSet.delete(k);
const p = projection?.[k];
if (
/** if field is omitted */
p?.sign === '-' ||
/** if no projection defined for this field and includeDefaultFields is true and the field is exclusive */
(!p && field.exclusive)) {
if (!needIncludes)
excludes.push(fieldPath);
continue;
}
if (needIncludes && p && !includes.includes(fieldPath)) {
if (!getNeedIncludes(p?.projection)) {
includes.push(fieldPath);
}
}
if (field.type instanceof ComplexType &&
typeof p?.projection === 'object') {
prepare(field.type, includes, excludes, fieldPath, p.projection);
}
}
if (dataType.additionalFields) {
for (k of projectionKeysSet.values()) {
const n = projection?.[k];
fieldPath = curPath + (curPath ? '.' : '') + k;
if (n?.sign === '-') {
if (!needIncludes)
excludes.push(fieldPath);
}
else
includes.push(fieldPath);
}
}
}