Last active
November 20, 2023 19:16
-
-
Save hellendag/2aa9ad1f9b771f38802760c269bb1b76 to your computer and use it in GitHub Desktop.
Merge mocked GraphQL resolvers
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
// @flow | |
type ResolvedScalar = string | number | boolean | null; | |
type ResolvedValue = | |
| ResolvedScalar | |
| Array<ResolvedValue> | |
| {[key: string]: ResolvedValue}; | |
type ResolverFunction = (...args: Array<any>) => ResolvedValue; | |
export type ResolverMap = { | |
[key: string]: () => {[key: string]: ResolvedValue | ResolverFunction} | null, | |
}; | |
/** | |
* Given a map of mock GraphQL resolver functions, merge in a map of | |
* desired mocks. Generally, `target` will be the default mocked values, | |
* and `input` will be the values desired for a portal example or Jest tests. | |
*/ | |
const mergeResolvers = (target: ResolverMap, input: ResolverMap) => { | |
const inputTypenames = Object.keys(input); | |
const merged: ResolverMap = inputTypenames.reduce( | |
(accum, key) => { | |
const inputResolver = input[key]; | |
if (target.hasOwnProperty(key)) { | |
const targetResolver = target[key]; | |
const resolvedInput = inputResolver(); | |
const resolvedTarget = targetResolver(); | |
if ( | |
!!resolvedTarget && | |
!!resolvedInput && | |
typeof resolvedTarget === 'object' && | |
typeof resolvedInput === 'object' && | |
!Array.isArray(resolvedTarget) && | |
!Array.isArray(resolvedInput) | |
) { | |
const newValue = {...resolvedTarget, ...resolvedInput}; | |
return { | |
...accum, | |
[key]: () => newValue, | |
}; | |
} | |
} | |
return {...accum, [key]: inputResolver}; | |
}, | |
{...target}, | |
); | |
return merged; | |
}; | |
export default mergeResolvers; |
would appreciate your review of the above and whether you're okay to merge this!
This snippet of code seriously saved my day !!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI, my colleague has submitted this to
graphql-tools
in ardatan/graphql-tools#1084Thanks for sharing it with the world.