-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
use-masked-errors.ts
66 lines (58 loc) · 2.11 KB
/
use-masked-errors.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { handleStreamOrSingleExecutionResult, Plugin } from '@envelop/types';
import { ExecutionResult, GraphQLError } from 'graphql';
export const DEFAULT_ERROR_MESSAGE = 'Unexpected error.';
export class EnvelopError extends GraphQLError {
constructor(message: string, extensions?: Record<string, any>) {
super(message, undefined, undefined, undefined, undefined, undefined, extensions);
}
}
export type FormatErrorHandler = (error: GraphQLError | unknown, message: string) => GraphQLError;
export const formatError: FormatErrorHandler = (err, message) => {
if (err instanceof GraphQLError) {
if (err.originalError && err.originalError instanceof EnvelopError === false) {
return new GraphQLError(message, err.nodes, err.source, err.positions, err.path, undefined);
}
return err;
}
return new GraphQLError(message);
};
export type UseMaskedErrorsOpts = {
formatError?: FormatErrorHandler;
errorMessage?: string;
};
const makeHandleResult =
(format: FormatErrorHandler, message: string) =>
({ result, setResult }: { result: ExecutionResult; setResult: (result: ExecutionResult) => void }) => {
if (result.errors != null) {
setResult({ ...result, errors: result.errors.map(error => format(error, message)) });
}
};
export const useMaskedErrors = (opts?: UseMaskedErrorsOpts): Plugin => {
const format = opts?.formatError ?? formatError;
const message = opts?.errorMessage || DEFAULT_ERROR_MESSAGE;
const handleResult = makeHandleResult(format, message);
return {
onPluginInit(context) {
context.registerContextErrorHandler(({ error, setError }) => {
setError(formatError(error, message));
});
},
onExecute() {
return {
onExecuteDone(payload) {
return handleStreamOrSingleExecutionResult(payload, handleResult);
},
};
},
onSubscribe() {
return {
onSubscribeResult(payload) {
return handleStreamOrSingleExecutionResult(payload, handleResult);
},
onSubscribeError({ error, setError }) {
setError(formatError(error, message));
},
};
},
};
};