import { GraphQLError } from 'graphql' import type { Plugin } from 'graphql-yoga' import { handleStreamOrSingleExecutionResult } from 'graphql-yoga' import { CedarError } from '@cedarjs/api' import type { Logger } from '@cedarjs/api/logger' import type { CedarGraphQLContext } from '../types.js' /** * Converts CedarErrors to GraphQLErrors * * This is a workaround for the fact that graphql-yoga doesn't support custom error types. * * Yoga automatically masks unexpected errors and prevents leaking sensitive information to clients. * * Since CedarErrors (such as ServiceValidation errors) are expected, * we need to convert them to GraphQLErrors so that they are not masked. * * See: https://the-guild.dev/graphql/yoga-server/docs/features/error-masking * * @param logger * @returns ExecutionResult */ export const useCedarError = (logger: Logger): Plugin => { return { async onExecute() { return { onExecuteDone(payload) { return handleStreamOrSingleExecutionResult( payload, ({ result, setResult }) => { const errors = result.errors?.map((error) => { if (error.originalError instanceof CedarError) { logger.debug( { custom: { name: error.originalError.name } }, 'Converting CedarError to GraphQLError', ) return new GraphQLError(error.message, { extensions: error.extensions, }) } else { return error } }) // be certain to return the complete result // and not just the data or the errors // because defer, stream and AsyncIterator results // need to be returned as is setResult({ ...result, errors, extensions: result.extensions || {}, }) }, ) }, } }, } }