Using currying or higher order functions with custom resolvers.
For example I what to send all my errors to Sentry.
// src/shared/withSentry.js
import * as Sentry from '@sentry/node';
const config = {
dsn: process.env.SENTRY_DSN,
};
Sentry.init(config);
export const withSentry = (customFunction) => async (
event,
ctx,
) => {
try {
return await customFunction(event, ctx);
} catch (error) {
if (error) {
console.error(error.message);
console.error(JSON.stringify(error.message, null, 2));
}
Sentry.withScope(scope => {
scope.setExtras({
event,
rawEvent: JSON.stringify(event),
ctx,
functionName: customFunction?.name,
error,
});
Sentry.captureMessage(customFunction.name);
});
await Sentry.flush(2000);
throw error;
}
};
//----
//
const myResolver = async (
even,
ctx,
) => {
const shouldThrowError = event.data?.shouldThrowError;
if (!!shouldThrowError) {
throw new Error('Test error');
}
return {
data: {
success: true,
},
};
};
export default withSentry(myResolver);