UNPKG

@omnigraph/odata

Version:
54 lines (53 loc) 2.47 kB
import { isAbstractType } from 'graphql'; import { simplifyParsedResolveInfoFragmentWithType, } from 'graphql-parse-resolve-info'; import { getDirectiveExtensions } from '@graphql-tools/utils'; import { URLSearchParams } from '@whatwg-node/fetch'; import { QUERY_OPTIONS_FIELDS } from './QueryOptionsFields.js'; export function prepareSearchParams({ fragment, schema, expandNavProps, }) { const fragmentTypeNames = Object.keys(fragment.fieldsByTypeName); const returnType = schema.getType(fragmentTypeNames[0]); const { args, fields } = simplifyParsedResolveInfoFragmentWithType(fragment, returnType); const searchParams = new URLSearchParams(); if ('queryOptions' in args) { const { queryOptions } = args; for (const param in 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 = !isAbstractType(returnType); if (isSelectable) { const returnTypeDirectives = 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; }