Skip to content

Instantly share code, notes, and snippets.

@hellendag
Last active November 20, 2023 19:16
Show Gist options
  • Select an option

  • Save hellendag/2aa9ad1f9b771f38802760c269bb1b76 to your computer and use it in GitHub Desktop.

Select an option

Save hellendag/2aa9ad1f9b771f38802760c269bb1b76 to your computer and use it in GitHub Desktop.
Merge mocked GraphQL resolvers
// @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;
@jamesreggio
Copy link
Copy Markdown

FYI, my colleague has submitted this to graphql-tools in ardatan/graphql-tools#1084

Thanks for sharing it with the world.

@finnigantime
Copy link
Copy Markdown

would appreciate your review of the above and whether you're okay to merge this!

@Renaud009
Copy link
Copy Markdown

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