Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Last active March 6, 2021 13:28
Show Gist options
  • Save n1ru4l/9b466a41ff0efc623cd17a109864d852 to your computer and use it in GitHub Desktop.
Save n1ru4l/9b466a41ff0efc623cd17a109864d852 to your computer and use it in GitHub Desktop.
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