Skip to content

Commit

Permalink
Add resolveQueryFromOperation and JSDoc comments
Browse files Browse the repository at this point in the history
  • Loading branch information
javamonn committed Nov 5, 2018
1 parent e445f90 commit 6c98833
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@ const { makeExecutableSchema, addMockFunctionsToSchema } = require('graphql-tool
const { graphql, printSchema, buildClientSchema } = require('graphql');
const RelayMockNetworkLayerError = require('./RelayMockNetworkLayerError');

module.exports = function getNetworkLayer({ schema, mocks, resolvers }) {
/**
* @param {Object} networkConfig - The configuration for the mock network layer.
* @param {(string|Object)} networkConfig.schema - If string, the graphql schema SDL. If object, the JSON introspection query.
* @param {Object} networkConfig.mocks - Mock primative resolvers, passed directly to addMockFunctionsToSchema.
* @param {Object} networkConfig.resolvers - Default resolvers for a schema.
* @param {Object} [networkConfig.resolveQueryFromOperation] - If relay operation query text does not exist, used to resolve the query from the operation. Useful for persisted query support.
*/
function getNetworkLayer({ schema, mocks, resolvers, resolveQueryFromOperation }) {
return function fetchQuery(operation, variableValues) {
if (typeof schema === 'object' && schema.data) {
schema = printSchema(buildClientSchema(schema.data));
Expand All @@ -15,7 +22,16 @@ module.exports = function getNetworkLayer({ schema, mocks, resolvers }) {
// Add mocks, modifies schema in place
addMockFunctionsToSchema({ schema: executableSchema, mocks });

return graphql(executableSchema, operation.text, null, null, variableValues).then(
const query =
(resolveQueryFromOperation && resolveQueryFromOperation(operation)) || operation.text;

if (!query) {
throw new Error(
'Could not find query, ensure operation.text exists or pass resolveQueryFromOperation.'
);
}

return graphql(executableSchema, query, null, null, variableValues).then(
// Trigger Relay error in case of GraphQL errors (or errors in mutation response)
// See https://github.com/facebook/relay/issues/1816

Expand All @@ -27,4 +43,6 @@ module.exports = function getNetworkLayer({ schema, mocks, resolvers }) {
}
);
};
};
}

module.exports = getNetworkLayer;

0 comments on commit 6c98833

Please sign in to comment.