Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Last active Mar 6, 2021
Embed
What would you like to do?
GraphQL Logger Middleware
import { isAsyncIterable } from "@n1ru4l/push-pull-async-iterable-iterator";
type MaybePromise<T> = Promise<T> | T;
const map = <T, O>(map: (input: T) => Promise<O> | O) =>
async function* mapGenerator(asyncIterable: AsyncIterableIterator<T>) {
for await (const value of asyncIterable) {
yield map(value);
}
};
export const applyGraphQLMiddleware = <T>(apply: (target: T) => MaybePromise<T>) => (
input: MaybePromise<AsyncIterableIterator<T> | T>
): MaybePromise<AsyncIterableIterator<T> | T> => {
const handler = (
result: AsyncIterableIterator<T> | T
): AsyncIterableIterator<T> | MaybePromise<T> => {
if (isAsyncIterable(result)) {
return AsyncIteratorUtil.map(apply)(result);
} else {
return apply(result);
}
};
return input instanceof Promise ? input.then(handler) : handler(input);
};
// Usage
import { flow } from "fp-ts/function";
import { ExecutionResult, execute as originalExecute, subscribe as originalSubscribe } from "graphql";
const graphQLErrorLogger = (result: ExecutionResult): ExecutionResult => {
if (result.errors) {
for (const error of result.errors) {
console.error(error.originalError);
}
}
return result;
};
const execute = flow(
liveQueryStore.execute,
applyGraphQLMiddleware(graphQLErrorLogger)
);
const subscribe = flow(
originalSubscribe,
applyGraphQLMiddleware(graphQLErrorLogger)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment