@envelop/core
Version:
This is the core package for Envelop. You can find a complete documentation here: https://github.com/graphql-hive/envelop
68 lines (67 loc) • 2.43 kB
JavaScript
import { handleStreamOrSingleExecutionResult } from '../utils.js';
import { isGraphQLError } from './use-masked-errors.js';
const makeHandleResult = (errorHandler) => ({ result, args }) => {
const errors = result.errors ? [...result.errors] : [];
if ('incremental' in result && result.incremental) {
for (const increment of result.incremental) {
if (increment.errors) {
errors.push(...increment.errors);
}
}
}
if (errors.length) {
errorHandler({ errors, context: args, phase: 'execution' });
}
};
export const useErrorHandler = (errorHandler) => {
const handleResult = makeHandleResult(errorHandler);
return {
onParse() {
return function onParseEnd({ result, context }) {
if (result instanceof Error) {
errorHandler({ errors: [result], context, phase: 'parse' });
}
};
},
onValidate() {
return function onValidateEnd({ valid, result, context }) {
if (valid === false && result.length > 0) {
errorHandler({
errors: result,
context,
phase: 'validate',
});
}
};
},
onPluginInit({ registerContextErrorHandler }) {
registerContextErrorHandler(({ error, context }) => {
if (isGraphQLError(error)) {
errorHandler({ errors: [error], context, phase: 'context' });
}
else {
errorHandler({
// @ts-expect-error its not an error at this point so we just create a new one - can we handle this better?
errors: [new Error(error)],
context,
phase: 'context',
});
}
});
},
onExecute() {
return {
onExecuteDone(payload) {
return handleStreamOrSingleExecutionResult(payload, handleResult);
},
};
},
onSubscribe() {
return {
onSubscribeResult(payload) {
return handleStreamOrSingleExecutionResult(payload, handleResult);
},
};
},
};
};