@omnigraph/odata
Version:
57 lines (56 loc) • 2.65 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareSearchParams = prepareSearchParams;
const graphql_1 = require("graphql");
const graphql_parse_resolve_info_1 = require("graphql-parse-resolve-info");
const utils_1 = require("@graphql-tools/utils");
const fetch_1 = require("@whatwg-node/fetch");
const QueryOptionsFields_js_1 = require("./QueryOptionsFields.js");
function prepareSearchParams({ fragment, schema, expandNavProps, }) {
const fragmentTypeNames = Object.keys(fragment.fieldsByTypeName);
const returnType = schema.getType(fragmentTypeNames[0]);
const { args, fields } = (0, graphql_parse_resolve_info_1.simplifyParsedResolveInfoFragmentWithType)(fragment, returnType);
const searchParams = new fetch_1.URLSearchParams();
if ('queryOptions' in args) {
const { queryOptions } = args;
for (const param in QueryOptionsFields_js_1.QUERY_OPTIONS_FIELDS) {
if (param in queryOptions) {
searchParams.set('$' + param, queryOptions[param]);
}
}
}
// $select doesn't work with inherited types' fields. So if there is an inline fragment for
// implemented types, we cannot use $select
const isSelectable = !(0, graphql_1.isAbstractType)(returnType);
if (isSelectable) {
const returnTypeDirectives = (0, utils_1.getDirectiveExtensions)(returnType);
const entityInfo = returnTypeDirectives?.entityInfo?.[0];
const selectionFields = [];
const expandedFields = [];
for (const fieldName in fields) {
if (entityInfo.actualFields.includes(fieldName)) {
selectionFields.push(fieldName);
}
if (expandNavProps && entityInfo.navigationFields.includes(fieldName)) {
const searchParams = prepareSearchParams({
fragment: fields[fieldName],
schema,
expandNavProps,
});
const searchParamsStr = decodeURIComponent(searchParams.toString());
expandedFields.push(`${fieldName}(${searchParamsStr.split('&').join(';')})`);
selectionFields.push(fieldName);
}
}
if (!selectionFields.includes(entityInfo.identifierFieldName)) {
selectionFields.push(entityInfo.identifierFieldName);
}
if (selectionFields.length) {
searchParams.set('$select', selectionFields.join(','));
}
if (expandedFields.length) {
searchParams.set('$expand', expandedFields.join(','));
}
}
return searchParams;
}
;