UNPKG

@graphql-tools/utils

Version:

Common package containing utils and types for GraphQL tools

64 lines (63 loc) 2.3 kB
import { locatedError as _locatedError, GraphQLError, versionInfo, } from 'graphql'; const possibleGraphQLErrorProperties = [ 'message', 'locations', 'path', 'nodes', 'source', 'positions', 'originalError', 'name', 'stack', 'extensions', ]; export function isGraphQLErrorLike(error) { return (error != null && typeof error === 'object' && Object.keys(error).every(key => possibleGraphQLErrorProperties.includes(key))); } export function createGraphQLError(message, options) { if (options?.originalError && !(options.originalError instanceof Error) && isGraphQLErrorLike(options.originalError)) { options.originalError = createGraphQLError(options.originalError.message, options.originalError); } let error; if (versionInfo.major >= 16) { error = new GraphQLError(message, options); } else { error = new GraphQLError(message, options?.nodes, options?.source, options?.positions, options?.path, options?.originalError, options?.extensions); } if (options?.coordinate != null && !error.coordinate) { Object.defineProperty(error, 'coordinate', { value: options.coordinate, enumerable: true, configurable: true, }); } return error; } export function getSchemaCoordinate(error) { return error.coordinate; } export function locatedError(rawError, nodes, path, info) { const error = _locatedError(rawError, nodes, path); // `graphql` locatedError is only changing path and nodes if it is not already defined if (!error.coordinate && info) { // @ts-expect-error coordinate is readonly, but we don't want to recreate it just to add coordinate error.coordinate = `${info.parentType.name}.${info.fieldName}`; } return error; } export function relocatedError(originalError, path, info) { return createGraphQLError(originalError.message, { nodes: originalError.nodes, source: originalError.source, positions: originalError.positions, path: path == null ? originalError.path : path, originalError, extensions: originalError.extensions, coordinate: info ? `${info.parentType.name}.${info.fieldName}` : undefined, }); }