Last active
March 6, 2021 13:28
-
-
Save n1ru4l/9b466a41ff0efc623cd17a109864d852 to your computer and use it in GitHub Desktop.
GraphQL Logger Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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