Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@jamesreggio jamesreggio commented Mar 26, 2019

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

Thanks for sharing it with the world.

@finnigantime

This comment has been minimized.

Copy link

@finnigantime finnigantime commented Apr 10, 2019

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

@Renaud009

This comment has been minimized.

Copy link

@Renaud009 Renaud009 commented Nov 7, 2019

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