mockResolver
This is a function with which you can create resolvers for Query
fields and subfields.
const {
getExecutableSchema,
mockResolver,
} = require('@lola-tech/graphql-kimera');
const schema = `
type Query {
...
`;
const executableSchema = getExecutableSchema({
typeDefs: schema,
mockProvidersFn: (context) => ({
scenario: {
rockets: mockResolver(
// 1st argument: `resolverFactoryFn`
(store) => (_, { model }) => {
// `mocks` is the store containing the mocks for the `rockets` field.
const mockedRockets = store.get();
return model
? mockedRockets.filter((rocket) => rocket.model === model)
: mockedRockets;
},
// 2nd argument: `scenario`
[{ model: 'Shuttle' }, {}, { model: 'Shuttle' }] // Optional
),
},
}),
});
API
mockResolver(resolverFactoryFn, scenario)
mockResolver
accepts two arguments:
resolverFactoryFn
* is arequired
function that gets the field mocks store as its argument, and needs to return a resolver.- The field
scenario
, which is Optional.
Here's each argument in greater detail:
resolverFactoryFn
(store) => (info, args, ...) => {...}
- The argument passed to factory function is the field
store
: an object that contains the mocked data for the field we are defining the resolver for. The store defines aget
method that returns the mocked data. - The
store.get
method accepts an optionalstring
argument, that represents the path. - You need to always use the
store.get
method to retrieve data. - The factory function needs to return a valid resolver.
You can see an example of this in action on the Query Resolvers page.
scenario
An object that represents the scenario for the specific field we are mocking the resolver for.
If omitted, the field will be mocked as it would if no scenario was defined for this field.
Example
Let's use the following schema:
type Query {
launches(site: String!): [Launch]
}
type Launch {
id: ID!
site: String
rockets: [Rocket]
isBooked: Boolean!
}
type Rocket {
id: ID!
name: String
model: String
fuel: Fuel
}
enum Fuel {
PLASMA
ION
DILITHIUM
}
Here's an example of mocking a resolver for the launches
field of the Query
type.
const executableSchema = getExecutableSchema({
typeDefs: schema,
mockProvidersFn: (context) => ({
scenario: {
launches: mockResolver(
(store) => (_, { site }) => {
// Get all launches mocked
const launches = store.get();
// Get rockets from the first launch
const firstLaunchRockets = store.get('launches.0.rockets');
// ...
},
// `store.get()` will retrieve mocks that
// are build according to this scenario.
[{ site: 'Vandenberg Base Space' }, {}, {}, {}, {}]
),
},
builders: {
Launch: () => ({
site: 'Kennedy Space Center',
}),
},
}),
});