Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add resolveQueryFromOperation and JSDoc comments #8

Merged
merged 1 commit into from
Nov 5, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;