Initial commit
This commit is contained in:
commit
f47e08fdcb
2409 files changed
+363607
No files matched your search
+299
@@ -0,0 +1,299 @@
|
||||
'use strict';
|
||||
|
||||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
var _accepts = require('accepts');
|
||||
|
||||
var _accepts2 = _interopRequireDefault(_accepts);
|
||||
|
||||
var _graphql = require('graphql');
|
||||
|
||||
var _httpErrors = require('http-errors');
|
||||
|
||||
var _httpErrors2 = _interopRequireDefault(_httpErrors);
|
||||
|
||||
var _url = require('url');
|
||||
|
||||
var _url2 = _interopRequireDefault(_url);
|
||||
|
||||
var _parseBody = require('./parseBody');
|
||||
|
||||
var _renderGraphiQL = require('./renderGraphiQL');
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Middleware for express; takes an options object or function as input to
|
||||
* configure behavior, and returns an express middleware.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Used to configure the graphqlHTTP middleware by providing a schema
|
||||
* and other configuration options.
|
||||
*
|
||||
* Options can be provided as an Object, a Promise for an Object, or a Function
|
||||
* that returns an Object or a Promise for an Object.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* All information about a GraphQL request.
|
||||
*/
|
||||
module.exports = graphqlHTTP;
|
||||
function graphqlHTTP(options) {
|
||||
if (!options) {
|
||||
throw new Error('GraphQL middleware requires options.');
|
||||
}
|
||||
|
||||
return function graphqlMiddleware(request, response) {
|
||||
// Higher scoped variables are referred to at various stages in the
|
||||
// asynchronous state machine below.
|
||||
var params = void 0;
|
||||
var pretty = void 0;
|
||||
var formatErrorFn = void 0;
|
||||
var extensionsFn = void 0;
|
||||
var showGraphiQL = void 0;
|
||||
var query = void 0;
|
||||
|
||||
var documentAST = void 0;
|
||||
var variables = void 0;
|
||||
var operationName = void 0;
|
||||
|
||||
// Promises are used as a mechanism for capturing any thrown errors during
|
||||
// the asynchronous process below.
|
||||
|
||||
// Parse the Request to get GraphQL request parameters.
|
||||
return getGraphQLParams(request).then(function (graphQLParams) {
|
||||
params = graphQLParams;
|
||||
// Then, resolve the Options to get OptionsData.
|
||||
return typeof options === 'function' ? options(request, response, params) : options;
|
||||
}).then(function (optionsData) {
|
||||
// Assert that optionsData is in fact an Object.
|
||||
if (!optionsData || (typeof optionsData === 'undefined' ? 'undefined' : _typeof(optionsData)) !== 'object') {
|
||||
throw new Error('GraphQL middleware option function must return an options object ' + 'or a promise which will be resolved to an options object.');
|
||||
}
|
||||
|
||||
// Assert that schema is required.
|
||||
if (!optionsData.schema) {
|
||||
throw new Error('GraphQL middleware options must contain a schema.');
|
||||
}
|
||||
|
||||
// Collect information from the options data object.
|
||||
var schema = optionsData.schema;
|
||||
var context = optionsData.context || request;
|
||||
var rootValue = optionsData.rootValue;
|
||||
var graphiql = optionsData.graphiql;
|
||||
pretty = optionsData.pretty;
|
||||
formatErrorFn = optionsData.formatError;
|
||||
extensionsFn = optionsData.extensions;
|
||||
|
||||
var validationRules = _graphql.specifiedRules;
|
||||
if (optionsData.validationRules) {
|
||||
validationRules = validationRules.concat(optionsData.validationRules);
|
||||
}
|
||||
|
||||
// GraphQL HTTP only supports GET and POST methods.
|
||||
if (request.method !== 'GET' && request.method !== 'POST') {
|
||||
response.setHeader('Allow', 'GET, POST');
|
||||
throw (0, _httpErrors2.default)(405, 'GraphQL only supports GET and POST requests.');
|
||||
}
|
||||
|
||||
// Get GraphQL params from the request and POST body data.
|
||||
query = params.query;
|
||||
variables = params.variables;
|
||||
operationName = params.operationName;
|
||||
showGraphiQL = graphiql && canDisplayGraphiQL(request, params);
|
||||
|
||||
// If there is no query, but GraphiQL will be displayed, do not produce
|
||||
// a result, otherwise return a 400: Bad Request.
|
||||
if (!query) {
|
||||
if (showGraphiQL) {
|
||||
return null;
|
||||
}
|
||||
throw (0, _httpErrors2.default)(400, 'Must provide query string.');
|
||||
}
|
||||
|
||||
// GraphQL source.
|
||||
var source = new _graphql.Source(query, 'GraphQL request');
|
||||
|
||||
// Parse source to AST, reporting any syntax error.
|
||||
try {
|
||||
documentAST = (0, _graphql.parse)(source);
|
||||
} catch (syntaxError) {
|
||||
// Return 400: Bad Request if any syntax errors errors exist.
|
||||
response.statusCode = 400;
|
||||
return { errors: [syntaxError] };
|
||||
}
|
||||
|
||||
// Validate AST, reporting any errors.
|
||||
var validationErrors = (0, _graphql.validate)(schema, documentAST, validationRules);
|
||||
if (validationErrors.length > 0) {
|
||||
// Return 400: Bad Request if any validation errors exist.
|
||||
response.statusCode = 400;
|
||||
return { errors: validationErrors };
|
||||
}
|
||||
|
||||
// Only query operations are allowed on GET requests.
|
||||
if (request.method === 'GET') {
|
||||
// Determine if this GET request will perform a non-query.
|
||||
var operationAST = (0, _graphql.getOperationAST)(documentAST, operationName);
|
||||
if (operationAST && operationAST.operation !== 'query') {
|
||||
// If GraphiQL can be shown, do not perform this query, but
|
||||
// provide it to GraphiQL so that the requester may perform it
|
||||
// themselves if desired.
|
||||
if (showGraphiQL) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Otherwise, report a 405: Method Not Allowed error.
|
||||
response.setHeader('Allow', 'POST');
|
||||
throw (0, _httpErrors2.default)(405, 'Can only perform a ' + operationAST.operation + ' operation ' + 'from a POST request.');
|
||||
}
|
||||
}
|
||||
// Perform the execution, reporting any errors creating the context.
|
||||
try {
|
||||
return (0, _graphql.execute)(schema, documentAST, rootValue, context, variables, operationName);
|
||||
} catch (contextError) {
|
||||
// Return 400: Bad Request if any execution context errors exist.
|
||||
response.statusCode = 400;
|
||||
return { errors: [contextError] };
|
||||
}
|
||||
}).then(function (result) {
|
||||
// Collect and apply any metadata extensions if a function was provided.
|
||||
// http://facebook.github.io/graphql/#sec-Response-Format
|
||||
if (result && extensionsFn) {
|
||||
return Promise.resolve(extensionsFn({
|
||||
document: documentAST,
|
||||
variables: variables,
|
||||
operationName: operationName,
|
||||
result: result
|
||||
})).then(function (extensions) {
|
||||
if (extensions && (typeof extensions === 'undefined' ? 'undefined' : _typeof(extensions)) === 'object') {
|
||||
result.extensions = extensions;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}).catch(function (error) {
|
||||
// If an error was caught, report the httpError status, or 500.
|
||||
response.statusCode = error.status || 500;
|
||||
return { errors: [error] };
|
||||
}).then(function (result) {
|
||||
// If no data was included in the result, that indicates a runtime query
|
||||
// error, indicate as such with a generic status code.
|
||||
// Note: Information about the error itself will still be contained in
|
||||
// the resulting JSON payload.
|
||||
// http://facebook.github.io/graphql/#sec-Data
|
||||
if (response.statusCode === 200 && result && !result.data) {
|
||||
response.statusCode = 500;
|
||||
}
|
||||
// Format any encountered errors.
|
||||
if (result && result.errors) {
|
||||
result.errors = result.errors.map(formatErrorFn || _graphql.formatError);
|
||||
}
|
||||
|
||||
// If allowed to show GraphiQL, present it instead of JSON.
|
||||
if (showGraphiQL) {
|
||||
var payload = (0, _renderGraphiQL.renderGraphiQL)({
|
||||
query: query,
|
||||
variables: variables,
|
||||
operationName: operationName,
|
||||
result: result
|
||||
});
|
||||
return sendResponse(response, 'text/html', payload);
|
||||
}
|
||||
|
||||
// At this point, result is guaranteed to exist, as the only scenario
|
||||
// where it will not is when showGraphiQL is true.
|
||||
if (!result) {
|
||||
throw (0, _httpErrors2.default)(500, 'Internal Error');
|
||||
}
|
||||
|
||||
// If "pretty" JSON isn't requested, and the server provides a
|
||||
// response.json method (express), use that directly.
|
||||
// Otherwise use the simplified sendResponse method.
|
||||
if (!pretty && typeof response.json === 'function') {
|
||||
response.json(result);
|
||||
} else {
|
||||
var _payload = JSON.stringify(result, null, pretty ? 2 : 0);
|
||||
sendResponse(response, 'application/json', _payload);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Provided a "Request" provided by express or connect (typically a node style
|
||||
* HTTPClientRequest), Promise the GraphQL request parameters.
|
||||
*/
|
||||
module.exports.getGraphQLParams = getGraphQLParams;
|
||||
function getGraphQLParams(request) {
|
||||
return (0, _parseBody.parseBody)(request).then(function (bodyData) {
|
||||
var urlData = request.url && _url2.default.parse(request.url, true).query || {};
|
||||
return parseGraphQLParams(urlData, bodyData);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to get the GraphQL params from the request.
|
||||
*/
|
||||
function parseGraphQLParams(urlData, bodyData) {
|
||||
// GraphQL Query string.
|
||||
var query = urlData.query || bodyData.query;
|
||||
if (typeof query !== 'string') {
|
||||
query = null;
|
||||
}
|
||||
|
||||
// Parse the variables if needed.
|
||||
var variables = urlData.variables || bodyData.variables;
|
||||
if (variables && typeof variables === 'string') {
|
||||
try {
|
||||
variables = JSON.parse(variables);
|
||||
} catch (error) {
|
||||
throw (0, _httpErrors2.default)(400, 'Variables are invalid JSON.');
|
||||
}
|
||||
} else if ((typeof variables === 'undefined' ? 'undefined' : _typeof(variables)) !== 'object') {
|
||||
variables = null;
|
||||
}
|
||||
|
||||
// Name of GraphQL operation to execute.
|
||||
var operationName = urlData.operationName || bodyData.operationName;
|
||||
if (typeof operationName !== 'string') {
|
||||
operationName = null;
|
||||
}
|
||||
|
||||
var raw = urlData.raw !== undefined || bodyData.raw !== undefined;
|
||||
|
||||
return { query: query, variables: variables, operationName: operationName, raw: raw };
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to determine if GraphiQL can be displayed.
|
||||
*/
|
||||
function canDisplayGraphiQL(request, params) {
|
||||
// If `raw` exists, GraphiQL mode is not enabled.
|
||||
// Allowed to show GraphiQL if not requested as raw and this request
|
||||
// prefers HTML over JSON.
|
||||
return !params.raw && (0, _accepts2.default)(request).types(['json', 'html']) === 'html';
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function for sending a response using only the core Node server APIs.
|
||||
*/
|
||||
function sendResponse(response, type, data) {
|
||||
var chunk = new Buffer(data, 'utf8');
|
||||
response.setHeader('Content-Type', type + '; charset=utf-8');
|
||||
response.setHeader('Content-Length', String(chunk.length));
|
||||
response.end(chunk);
|
||||
}
|
||||
+411
@@ -0,0 +1,411 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import accepts from 'accepts';
|
||||
import {
|
||||
Source,
|
||||
parse,
|
||||
validate,
|
||||
execute,
|
||||
formatError,
|
||||
getOperationAST,
|
||||
specifiedRules,
|
||||
} from 'graphql';
|
||||
import httpError from 'http-errors';
|
||||
import url from 'url';
|
||||
|
||||
import { parseBody } from './parseBody';
|
||||
import { renderGraphiQL } from './renderGraphiQL';
|
||||
|
||||
import type { DocumentNode, GraphQLError, GraphQLSchema } from 'graphql';
|
||||
import type { $Request, $Response } from 'express';
|
||||
|
||||
/**
|
||||
* Used to configure the graphqlHTTP middleware by providing a schema
|
||||
* and other configuration options.
|
||||
*
|
||||
* Options can be provided as an Object, a Promise for an Object, or a Function
|
||||
* that returns an Object or a Promise for an Object.
|
||||
*/
|
||||
export type Options =
|
||||
| ((
|
||||
request: $Request,
|
||||
response: $Response,
|
||||
params?: GraphQLParams,
|
||||
) => OptionsResult)
|
||||
| OptionsResult;
|
||||
export type OptionsResult = OptionsData | Promise<OptionsData>;
|
||||
export type OptionsData = {
|
||||
/**
|
||||
* A GraphQL schema from graphql-js.
|
||||
*/
|
||||
schema: GraphQLSchema,
|
||||
|
||||
/**
|
||||
* A value to pass as the context to the graphql() function.
|
||||
*/
|
||||
context?: ?mixed,
|
||||
|
||||
/**
|
||||
* An object to pass as the rootValue to the graphql() function.
|
||||
*/
|
||||
rootValue?: ?mixed,
|
||||
|
||||
/**
|
||||
* A boolean to configure whether the output should be pretty-printed.
|
||||
*/
|
||||
pretty?: ?boolean,
|
||||
|
||||
/**
|
||||
* An optional function which will be used to format any errors produced by
|
||||
* fulfilling a GraphQL operation. If no function is provided, GraphQL's
|
||||
* default spec-compliant `formatError` function will be used.
|
||||
*/
|
||||
formatError?: ?(error: GraphQLError) => mixed,
|
||||
|
||||
/**
|
||||
* An optional array of validation rules that will be applied on the document
|
||||
* in additional to those defined by the GraphQL spec.
|
||||
*/
|
||||
validationRules?: ?Array<mixed>,
|
||||
|
||||
/**
|
||||
* An optional function for adding additional metadata to the GraphQL response
|
||||
* as a key-value object. The result will be added to "extensions" field in
|
||||
* the resulting JSON. This is often a useful place to add development time
|
||||
* info such as the runtime of a query or the amount of resources consumed.
|
||||
*
|
||||
* Information about the request is provided to be used.
|
||||
*
|
||||
* This function may be async.
|
||||
*/
|
||||
extensions?: ?(info: RequestInfo) => { [key: string]: mixed },
|
||||
|
||||
/**
|
||||
* A boolean to optionally enable GraphiQL mode.
|
||||
*/
|
||||
graphiql?: ?boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* All information about a GraphQL request.
|
||||
*/
|
||||
export type RequestInfo = {
|
||||
/**
|
||||
* The parsed GraphQL document.
|
||||
*/
|
||||
document: ?DocumentNode,
|
||||
|
||||
/**
|
||||
* The variable values used at runtime.
|
||||
*/
|
||||
variables: ?{ [name: string]: mixed },
|
||||
|
||||
/**
|
||||
* The (optional) operation name requested.
|
||||
*/
|
||||
operationName: ?string,
|
||||
|
||||
/**
|
||||
* The result of executing the operation.
|
||||
*/
|
||||
result: ?mixed,
|
||||
};
|
||||
|
||||
type Middleware = (request: $Request, response: $Response) => Promise<void>;
|
||||
|
||||
/**
|
||||
* Middleware for express; takes an options object or function as input to
|
||||
* configure behavior, and returns an express middleware.
|
||||
*/
|
||||
module.exports = graphqlHTTP;
|
||||
function graphqlHTTP(options: Options): Middleware {
|
||||
if (!options) {
|
||||
throw new Error('GraphQL middleware requires options.');
|
||||
}
|
||||
|
||||
return function graphqlMiddleware(request: $Request, response: $Response) {
|
||||
// Higher scoped variables are referred to at various stages in the
|
||||
// asynchronous state machine below.
|
||||
let params;
|
||||
let pretty;
|
||||
let formatErrorFn;
|
||||
let extensionsFn;
|
||||
let showGraphiQL;
|
||||
let query;
|
||||
|
||||
let documentAST;
|
||||
let variables;
|
||||
let operationName;
|
||||
|
||||
// Promises are used as a mechanism for capturing any thrown errors during
|
||||
// the asynchronous process below.
|
||||
|
||||
// Parse the Request to get GraphQL request parameters.
|
||||
return getGraphQLParams(request)
|
||||
.then(graphQLParams => {
|
||||
params = graphQLParams;
|
||||
// Then, resolve the Options to get OptionsData.
|
||||
return typeof options === 'function'
|
||||
? options(request, response, params)
|
||||
: options;
|
||||
})
|
||||
.then(optionsData => {
|
||||
// Assert that optionsData is in fact an Object.
|
||||
if (!optionsData || typeof optionsData !== 'object') {
|
||||
throw new Error(
|
||||
'GraphQL middleware option function must return an options object ' +
|
||||
'or a promise which will be resolved to an options object.',
|
||||
);
|
||||
}
|
||||
|
||||
// Assert that schema is required.
|
||||
if (!optionsData.schema) {
|
||||
throw new Error('GraphQL middleware options must contain a schema.');
|
||||
}
|
||||
|
||||
// Collect information from the options data object.
|
||||
const schema = optionsData.schema;
|
||||
const context = optionsData.context || request;
|
||||
const rootValue = optionsData.rootValue;
|
||||
const graphiql = optionsData.graphiql;
|
||||
pretty = optionsData.pretty;
|
||||
formatErrorFn = optionsData.formatError;
|
||||
extensionsFn = optionsData.extensions;
|
||||
|
||||
let validationRules = specifiedRules;
|
||||
if (optionsData.validationRules) {
|
||||
validationRules = validationRules.concat(optionsData.validationRules);
|
||||
}
|
||||
|
||||
// GraphQL HTTP only supports GET and POST methods.
|
||||
if (request.method !== 'GET' && request.method !== 'POST') {
|
||||
response.setHeader('Allow', 'GET, POST');
|
||||
throw httpError(405, 'GraphQL only supports GET and POST requests.');
|
||||
}
|
||||
|
||||
// Get GraphQL params from the request and POST body data.
|
||||
query = params.query;
|
||||
variables = params.variables;
|
||||
operationName = params.operationName;
|
||||
showGraphiQL = graphiql && canDisplayGraphiQL(request, params);
|
||||
|
||||
// If there is no query, but GraphiQL will be displayed, do not produce
|
||||
// a result, otherwise return a 400: Bad Request.
|
||||
if (!query) {
|
||||
if (showGraphiQL) {
|
||||
return null;
|
||||
}
|
||||
throw httpError(400, 'Must provide query string.');
|
||||
}
|
||||
|
||||
// GraphQL source.
|
||||
const source = new Source(query, 'GraphQL request');
|
||||
|
||||
// Parse source to AST, reporting any syntax error.
|
||||
try {
|
||||
documentAST = parse(source);
|
||||
} catch (syntaxError) {
|
||||
// Return 400: Bad Request if any syntax errors errors exist.
|
||||
response.statusCode = 400;
|
||||
return { errors: [syntaxError] };
|
||||
}
|
||||
|
||||
// Validate AST, reporting any errors.
|
||||
const validationErrors = validate(schema, documentAST, validationRules);
|
||||
if (validationErrors.length > 0) {
|
||||
// Return 400: Bad Request if any validation errors exist.
|
||||
response.statusCode = 400;
|
||||
return { errors: validationErrors };
|
||||
}
|
||||
|
||||
// Only query operations are allowed on GET requests.
|
||||
if (request.method === 'GET') {
|
||||
// Determine if this GET request will perform a non-query.
|
||||
const operationAST = getOperationAST(documentAST, operationName);
|
||||
if (operationAST && operationAST.operation !== 'query') {
|
||||
// If GraphiQL can be shown, do not perform this query, but
|
||||
// provide it to GraphiQL so that the requester may perform it
|
||||
// themselves if desired.
|
||||
if (showGraphiQL) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Otherwise, report a 405: Method Not Allowed error.
|
||||
response.setHeader('Allow', 'POST');
|
||||
throw httpError(
|
||||
405,
|
||||
`Can only perform a ${operationAST.operation} operation ` +
|
||||
'from a POST request.',
|
||||
);
|
||||
}
|
||||
}
|
||||
// Perform the execution, reporting any errors creating the context.
|
||||
try {
|
||||
return execute(
|
||||
schema,
|
||||
documentAST,
|
||||
rootValue,
|
||||
context,
|
||||
variables,
|
||||
operationName,
|
||||
);
|
||||
} catch (contextError) {
|
||||
// Return 400: Bad Request if any execution context errors exist.
|
||||
response.statusCode = 400;
|
||||
return { errors: [contextError] };
|
||||
}
|
||||
})
|
||||
.then(result => {
|
||||
// Collect and apply any metadata extensions if a function was provided.
|
||||
// http://facebook.github.io/graphql/#sec-Response-Format
|
||||
if (result && extensionsFn) {
|
||||
return Promise.resolve(
|
||||
extensionsFn({
|
||||
document: documentAST,
|
||||
variables,
|
||||
operationName,
|
||||
result,
|
||||
}),
|
||||
).then(extensions => {
|
||||
if (extensions && typeof extensions === 'object') {
|
||||
(result: any).extensions = extensions;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
return result;
|
||||
})
|
||||
.catch(error => {
|
||||
// If an error was caught, report the httpError status, or 500.
|
||||
response.statusCode = error.status || 500;
|
||||
return { errors: [error] };
|
||||
})
|
||||
.then(result => {
|
||||
// If no data was included in the result, that indicates a runtime query
|
||||
// error, indicate as such with a generic status code.
|
||||
// Note: Information about the error itself will still be contained in
|
||||
// the resulting JSON payload.
|
||||
// http://facebook.github.io/graphql/#sec-Data
|
||||
if (response.statusCode === 200 && result && !result.data) {
|
||||
response.statusCode = 500;
|
||||
}
|
||||
// Format any encountered errors.
|
||||
if (result && result.errors) {
|
||||
(result: any).errors = result.errors.map(
|
||||
formatErrorFn || formatError,
|
||||
);
|
||||
}
|
||||
|
||||
// If allowed to show GraphiQL, present it instead of JSON.
|
||||
if (showGraphiQL) {
|
||||
const payload = renderGraphiQL({
|
||||
query,
|
||||
variables,
|
||||
operationName,
|
||||
result,
|
||||
});
|
||||
return sendResponse(response, 'text/html', payload);
|
||||
}
|
||||
|
||||
// At this point, result is guaranteed to exist, as the only scenario
|
||||
// where it will not is when showGraphiQL is true.
|
||||
if (!result) {
|
||||
throw httpError(500, 'Internal Error');
|
||||
}
|
||||
|
||||
// If "pretty" JSON isn't requested, and the server provides a
|
||||
// response.json method (express), use that directly.
|
||||
// Otherwise use the simplified sendResponse method.
|
||||
if (!pretty && typeof response.json === 'function') {
|
||||
response.json(result);
|
||||
} else {
|
||||
const payload = JSON.stringify(result, null, pretty ? 2 : 0);
|
||||
sendResponse(response, 'application/json', payload);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export type GraphQLParams = {
|
||||
query: ?string,
|
||||
variables: ?{ [name: string]: mixed },
|
||||
operationName: ?string,
|
||||
raw: ?boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* Provided a "Request" provided by express or connect (typically a node style
|
||||
* HTTPClientRequest), Promise the GraphQL request parameters.
|
||||
*/
|
||||
module.exports.getGraphQLParams = getGraphQLParams;
|
||||
function getGraphQLParams(request: $Request): Promise<GraphQLParams> {
|
||||
return parseBody(request).then(bodyData => {
|
||||
const urlData = (request.url && url.parse(request.url, true).query) || {};
|
||||
return parseGraphQLParams(urlData, bodyData);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to get the GraphQL params from the request.
|
||||
*/
|
||||
function parseGraphQLParams(
|
||||
urlData: { [param: string]: mixed },
|
||||
bodyData: { [param: string]: mixed },
|
||||
): GraphQLParams {
|
||||
// GraphQL Query string.
|
||||
let query = urlData.query || bodyData.query;
|
||||
if (typeof query !== 'string') {
|
||||
query = null;
|
||||
}
|
||||
|
||||
// Parse the variables if needed.
|
||||
let variables = urlData.variables || bodyData.variables;
|
||||
if (variables && typeof variables === 'string') {
|
||||
try {
|
||||
variables = JSON.parse(variables);
|
||||
} catch (error) {
|
||||
throw httpError(400, 'Variables are invalid JSON.');
|
||||
}
|
||||
} else if (typeof variables !== 'object') {
|
||||
variables = null;
|
||||
}
|
||||
|
||||
// Name of GraphQL operation to execute.
|
||||
let operationName = urlData.operationName || bodyData.operationName;
|
||||
if (typeof operationName !== 'string') {
|
||||
operationName = null;
|
||||
}
|
||||
|
||||
const raw = urlData.raw !== undefined || bodyData.raw !== undefined;
|
||||
|
||||
return { query, variables, operationName, raw };
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to determine if GraphiQL can be displayed.
|
||||
*/
|
||||
function canDisplayGraphiQL(request: $Request, params: GraphQLParams): boolean {
|
||||
// If `raw` exists, GraphiQL mode is not enabled.
|
||||
// Allowed to show GraphiQL if not requested as raw and this request
|
||||
// prefers HTML over JSON.
|
||||
return !params.raw && accepts(request).types(['json', 'html']) === 'html';
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function for sending a response using only the core Node server APIs.
|
||||
*/
|
||||
function sendResponse(response: $Response, type: string, data: string): void {
|
||||
const chunk = new Buffer(data, 'utf8');
|
||||
response.setHeader('Content-Type', type + '; charset=utf-8');
|
||||
response.setHeader('Content-Length', String(chunk.length));
|
||||
response.end(chunk);
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
exports.parseBody = parseBody;
|
||||
|
||||
var _contentType = require('content-type');
|
||||
|
||||
var _contentType2 = _interopRequireDefault(_contentType);
|
||||
|
||||
var _rawBody = require('raw-body');
|
||||
|
||||
var _rawBody2 = _interopRequireDefault(_rawBody);
|
||||
|
||||
var _httpErrors = require('http-errors');
|
||||
|
||||
var _httpErrors2 = _interopRequireDefault(_httpErrors);
|
||||
|
||||
var _querystring = require('querystring');
|
||||
|
||||
var _querystring2 = _interopRequireDefault(_querystring);
|
||||
|
||||
var _zlib = require('zlib');
|
||||
|
||||
var _zlib2 = _interopRequireDefault(_zlib);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Provided a "Request" provided by express or connect (typically a node style
|
||||
* HTTPClientRequest), Promise the body data contained.
|
||||
*/
|
||||
function parseBody(req) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var body = req.body;
|
||||
|
||||
// If express has already parsed a body as a keyed object, use it.
|
||||
if ((typeof body === 'undefined' ? 'undefined' : _typeof(body)) === 'object' && !(body instanceof Buffer)) {
|
||||
return resolve(body);
|
||||
}
|
||||
|
||||
// Skip requests without content types.
|
||||
if (req.headers['content-type'] === undefined) {
|
||||
return resolve({});
|
||||
}
|
||||
|
||||
var typeInfo = _contentType2.default.parse(req);
|
||||
|
||||
// If express has already parsed a body as a string, and the content-type
|
||||
// was application/graphql, parse the string body.
|
||||
if (typeof body === 'string' && typeInfo.type === 'application/graphql') {
|
||||
return resolve(graphqlParser(body));
|
||||
}
|
||||
|
||||
// Already parsed body we didn't recognise? Parse nothing.
|
||||
if (body) {
|
||||
return resolve({});
|
||||
}
|
||||
|
||||
// Use the correct body parser based on Content-Type header.
|
||||
switch (typeInfo.type) {
|
||||
case 'application/graphql':
|
||||
return read(req, typeInfo, graphqlParser, resolve, reject);
|
||||
case 'application/json':
|
||||
return read(req, typeInfo, jsonEncodedParser, resolve, reject);
|
||||
case 'application/x-www-form-urlencoded':
|
||||
return read(req, typeInfo, urlEncodedParser, resolve, reject);
|
||||
}
|
||||
|
||||
// If no Content-Type header matches, parse nothing.
|
||||
return resolve({});
|
||||
});
|
||||
}
|
||||
|
||||
function jsonEncodedParser(body) {
|
||||
if (jsonObjRegex.test(body)) {
|
||||
/* eslint-disable no-empty */
|
||||
try {
|
||||
return JSON.parse(body);
|
||||
} catch (error) {}
|
||||
// Do nothing
|
||||
|
||||
/* eslint-enable no-empty */
|
||||
}
|
||||
throw (0, _httpErrors2.default)(400, 'POST body sent invalid JSON.');
|
||||
}
|
||||
|
||||
function urlEncodedParser(body) {
|
||||
return _querystring2.default.parse(body);
|
||||
}
|
||||
|
||||
function graphqlParser(body) {
|
||||
return { query: body };
|
||||
}
|
||||
|
||||
/**
|
||||
* RegExp to match an Object-opening brace "{" as the first non-space
|
||||
* in a string. Allowed whitespace is defined in RFC 7159:
|
||||
*
|
||||
* x20 Space
|
||||
* x09 Horizontal tab
|
||||
* x0A Line feed or New line
|
||||
* x0D Carriage return
|
||||
*/
|
||||
var jsonObjRegex = /^[\x20\x09\x0a\x0d]*\{/;
|
||||
|
||||
// Read and parse a request body.
|
||||
function read(req, typeInfo, parseFn, resolve, reject) {
|
||||
var charset = (typeInfo.parameters.charset || 'utf-8').toLowerCase();
|
||||
|
||||
// Assert charset encoding per JSON RFC 7159 sec 8.1
|
||||
if (charset.slice(0, 4) !== 'utf-') {
|
||||
throw (0, _httpErrors2.default)(415, 'Unsupported charset "' + charset.toUpperCase() + '".');
|
||||
}
|
||||
|
||||
// Get content-encoding (e.g. gzip)
|
||||
var contentEncoding = req.headers['content-encoding'];
|
||||
var encoding = typeof contentEncoding === 'string' ? contentEncoding.toLowerCase() : 'identity';
|
||||
var length = encoding === 'identity' ? req.headers['content-length'] : null;
|
||||
var limit = 100 * 1024; // 100kb
|
||||
var stream = decompressed(req, encoding);
|
||||
|
||||
// Read body from stream.
|
||||
(0, _rawBody2.default)(stream, { encoding: charset, length: length, limit: limit }, function (err, body) {
|
||||
if (err) {
|
||||
return reject(err.type === 'encoding.unsupported' ? (0, _httpErrors2.default)(415, 'Unsupported charset "' + charset.toUpperCase() + '".') : (0, _httpErrors2.default)(400, 'Invalid body: ' + err.message + '.'));
|
||||
}
|
||||
|
||||
try {
|
||||
// Decode and parse body.
|
||||
return resolve(parseFn(body));
|
||||
} catch (error) {
|
||||
return reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Return a decompressed stream, given an encoding.
|
||||
function decompressed(req, encoding) {
|
||||
switch (encoding) {
|
||||
case 'identity':
|
||||
return req;
|
||||
case 'deflate':
|
||||
return req.pipe(_zlib2.default.createInflate());
|
||||
case 'gzip':
|
||||
return req.pipe(_zlib2.default.createGunzip());
|
||||
}
|
||||
throw (0, _httpErrors2.default)(415, 'Unsupported content-encoding "' + encoding + '".');
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import contentType from 'content-type';
|
||||
import getBody from 'raw-body';
|
||||
import httpError from 'http-errors';
|
||||
import querystring from 'querystring';
|
||||
import zlib from 'zlib';
|
||||
|
||||
import type { $Request } from 'express';
|
||||
|
||||
/**
|
||||
* Provided a "Request" provided by express or connect (typically a node style
|
||||
* HTTPClientRequest), Promise the body data contained.
|
||||
*/
|
||||
export function parseBody(req: $Request): Promise<{ [param: string]: mixed }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = req.body;
|
||||
|
||||
// If express has already parsed a body as a keyed object, use it.
|
||||
if (typeof body === 'object' && !(body instanceof Buffer)) {
|
||||
return resolve((body: any));
|
||||
}
|
||||
|
||||
// Skip requests without content types.
|
||||
if (req.headers['content-type'] === undefined) {
|
||||
return resolve({});
|
||||
}
|
||||
|
||||
const typeInfo = contentType.parse(req);
|
||||
|
||||
// If express has already parsed a body as a string, and the content-type
|
||||
// was application/graphql, parse the string body.
|
||||
if (typeof body === 'string' && typeInfo.type === 'application/graphql') {
|
||||
return resolve(graphqlParser(body));
|
||||
}
|
||||
|
||||
// Already parsed body we didn't recognise? Parse nothing.
|
||||
if (body) {
|
||||
return resolve({});
|
||||
}
|
||||
|
||||
// Use the correct body parser based on Content-Type header.
|
||||
switch (typeInfo.type) {
|
||||
case 'application/graphql':
|
||||
return read(req, typeInfo, graphqlParser, resolve, reject);
|
||||
case 'application/json':
|
||||
return read(req, typeInfo, jsonEncodedParser, resolve, reject);
|
||||
case 'application/x-www-form-urlencoded':
|
||||
return read(req, typeInfo, urlEncodedParser, resolve, reject);
|
||||
}
|
||||
|
||||
// If no Content-Type header matches, parse nothing.
|
||||
return resolve({});
|
||||
});
|
||||
}
|
||||
|
||||
function jsonEncodedParser(body) {
|
||||
if (jsonObjRegex.test(body)) {
|
||||
/* eslint-disable no-empty */
|
||||
try {
|
||||
return JSON.parse(body);
|
||||
} catch (error) {
|
||||
// Do nothing
|
||||
}
|
||||
/* eslint-enable no-empty */
|
||||
}
|
||||
throw httpError(400, 'POST body sent invalid JSON.');
|
||||
}
|
||||
|
||||
function urlEncodedParser(body) {
|
||||
return querystring.parse(body);
|
||||
}
|
||||
|
||||
function graphqlParser(body) {
|
||||
return { query: body };
|
||||
}
|
||||
|
||||
/**
|
||||
* RegExp to match an Object-opening brace "{" as the first non-space
|
||||
* in a string. Allowed whitespace is defined in RFC 7159:
|
||||
*
|
||||
* x20 Space
|
||||
* x09 Horizontal tab
|
||||
* x0A Line feed or New line
|
||||
* x0D Carriage return
|
||||
*/
|
||||
const jsonObjRegex = /^[\x20\x09\x0a\x0d]*\{/;
|
||||
|
||||
// Read and parse a request body.
|
||||
function read(req, typeInfo, parseFn, resolve, reject) {
|
||||
const charset = (typeInfo.parameters.charset || 'utf-8').toLowerCase();
|
||||
|
||||
// Assert charset encoding per JSON RFC 7159 sec 8.1
|
||||
if (charset.slice(0, 4) !== 'utf-') {
|
||||
throw httpError(415, `Unsupported charset "${charset.toUpperCase()}".`);
|
||||
}
|
||||
|
||||
// Get content-encoding (e.g. gzip)
|
||||
const contentEncoding = req.headers['content-encoding'];
|
||||
const encoding =
|
||||
typeof contentEncoding === 'string'
|
||||
? contentEncoding.toLowerCase()
|
||||
: 'identity';
|
||||
const length = encoding === 'identity' ? req.headers['content-length'] : null;
|
||||
const limit = 100 * 1024; // 100kb
|
||||
const stream = decompressed(req, encoding);
|
||||
|
||||
// Read body from stream.
|
||||
getBody(stream, { encoding: charset, length, limit }, (err, body) => {
|
||||
if (err) {
|
||||
return reject(
|
||||
err.type === 'encoding.unsupported'
|
||||
? httpError(415, `Unsupported charset "${charset.toUpperCase()}".`)
|
||||
: httpError(400, `Invalid body: ${err.message}.`),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// Decode and parse body.
|
||||
return resolve(parseFn(body));
|
||||
} catch (error) {
|
||||
return reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Return a decompressed stream, given an encoding.
|
||||
function decompressed(req, encoding) {
|
||||
switch (encoding) {
|
||||
case 'identity':
|
||||
return req;
|
||||
case 'deflate':
|
||||
return req.pipe(zlib.createInflate());
|
||||
case 'gzip':
|
||||
return req.pipe(zlib.createGunzip());
|
||||
}
|
||||
throw httpError(415, `Unsupported content-encoding "${encoding}".`);
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.renderGraphiQL = renderGraphiQL;
|
||||
|
||||
|
||||
// Current latest version of GraphiQL.
|
||||
var GRAPHIQL_VERSION = '0.11.11';
|
||||
|
||||
// Ensures string values are safe to be used within a <script> tag.
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
function safeSerialize(data) {
|
||||
return data ? JSON.stringify(data).replace(/\//g, '\\/') : 'undefined';
|
||||
}
|
||||
|
||||
/**
|
||||
* When express-graphql receives a request which does not Accept JSON, but does
|
||||
* Accept HTML, it may present GraphiQL, the in-browser GraphQL explorer IDE.
|
||||
*
|
||||
* When shown, it will be pre-populated with the result of having executed the
|
||||
* requested query.
|
||||
*/
|
||||
function renderGraphiQL(data) {
|
||||
var queryString = data.query;
|
||||
var variablesString = data.variables ? JSON.stringify(data.variables, null, 2) : null;
|
||||
var resultString = data.result ? JSON.stringify(data.result, null, 2) : null;
|
||||
var operationName = data.operationName;
|
||||
|
||||
return '<!--\nThe request to this GraphQL server provided the header "Accept: text/html"\nand as a result has been presented GraphiQL - an in-browser IDE for\nexploring GraphQL.\n\nIf you wish to receive JSON, provide the header "Accept: application/json" or\nadd "&raw" to the end of the URL within a browser.\n-->\n<!DOCTYPE html>\n<html>\n<head>\n <meta charset="utf-8" />\n <title>GraphiQL</title>\n <meta name="robots" content="noindex" />\n <meta name="referrer" content="origin">\n <style>\n body {\n height: 100%;\n margin: 0;\n overflow: hidden;\n width: 100%;\n }\n #graphiql {\n height: 100vh;\n }\n </style>\n <link href="//cdn.jsdelivr.net/npm/graphiql@' + GRAPHIQL_VERSION + '/graphiql.css" rel="stylesheet" />\n <script src="//cdn.jsdelivr.net/es6-promise/4.0.5/es6-promise.auto.min.js"></script>\n <script src="//cdn.jsdelivr.net/fetch/0.9.0/fetch.min.js"></script>\n <script src="//cdn.jsdelivr.net/react/15.4.2/react.min.js"></script>\n <script src="//cdn.jsdelivr.net/react/15.4.2/react-dom.min.js"></script>\n <script src="//cdn.jsdelivr.net/npm/graphiql@' + GRAPHIQL_VERSION + '/graphiql.min.js"></script>\n</head>\n<body>\n <div id="graphiql">Loading...</div>\n <script>\n // Collect the URL parameters\n var parameters = {};\n window.location.search.substr(1).split(\'&\').forEach(function (entry) {\n var eq = entry.indexOf(\'=\');\n if (eq >= 0) {\n parameters[decodeURIComponent(entry.slice(0, eq))] =\n decodeURIComponent(entry.slice(eq + 1));\n }\n });\n\n // Produce a Location query string from a parameter object.\n function locationQuery(params) {\n return \'?\' + Object.keys(params).filter(function (key) {\n return Boolean(params[key]);\n }).map(function (key) {\n return encodeURIComponent(key) + \'=\' +\n encodeURIComponent(params[key]);\n }).join(\'&\');\n }\n\n // Derive a fetch URL from the current URL, sans the GraphQL parameters.\n var graphqlParamNames = {\n query: true,\n variables: true,\n operationName: true\n };\n\n var otherParams = {};\n for (var k in parameters) {\n if (parameters.hasOwnProperty(k) && graphqlParamNames[k] !== true) {\n otherParams[k] = parameters[k];\n }\n }\n var fetchURL = locationQuery(otherParams);\n\n // Defines a GraphQL fetcher using the fetch API.\n function graphQLFetcher(graphQLParams) {\n return fetch(fetchURL, {\n method: \'post\',\n headers: {\n \'Accept\': \'application/json\',\n \'Content-Type\': \'application/json\'\n },\n body: JSON.stringify(graphQLParams),\n credentials: \'include\',\n }).then(function (response) {\n return response.text();\n }).then(function (responseBody) {\n try {\n return JSON.parse(responseBody);\n } catch (error) {\n return responseBody;\n }\n });\n }\n\n // When the query and variables string is edited, update the URL bar so\n // that it can be easily shared.\n function onEditQuery(newQuery) {\n parameters.query = newQuery;\n updateURL();\n }\n\n function onEditVariables(newVariables) {\n parameters.variables = newVariables;\n updateURL();\n }\n\n function onEditOperationName(newOperationName) {\n parameters.operationName = newOperationName;\n updateURL();\n }\n\n function updateURL() {\n history.replaceState(null, null, locationQuery(parameters));\n }\n\n // Render <GraphiQL /> into the body.\n ReactDOM.render(\n React.createElement(GraphiQL, {\n fetcher: graphQLFetcher,\n onEditQuery: onEditQuery,\n onEditVariables: onEditVariables,\n onEditOperationName: onEditOperationName,\n query: ' + safeSerialize(queryString) + ',\n response: ' + safeSerialize(resultString) + ',\n variables: ' + safeSerialize(variablesString) + ',\n operationName: ' + safeSerialize(operationName) + ',\n }),\n document.getElementById(\'graphiql\')\n );\n </script>\n</body>\n</html>';
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
type GraphiQLData = {
|
||||
query: ?string,
|
||||
variables: ?{ [name: string]: mixed },
|
||||
operationName: ?string,
|
||||
result?: mixed,
|
||||
};
|
||||
|
||||
// Current latest version of GraphiQL.
|
||||
const GRAPHIQL_VERSION = '0.11.11';
|
||||
|
||||
// Ensures string values are safe to be used within a <script> tag.
|
||||
function safeSerialize(data) {
|
||||
return data ? JSON.stringify(data).replace(/\//g, '\\/') : 'undefined';
|
||||
}
|
||||
|
||||
/**
|
||||
* When express-graphql receives a request which does not Accept JSON, but does
|
||||
* Accept HTML, it may present GraphiQL, the in-browser GraphQL explorer IDE.
|
||||
*
|
||||
* When shown, it will be pre-populated with the result of having executed the
|
||||
* requested query.
|
||||
*/
|
||||
export function renderGraphiQL(data: GraphiQLData): string {
|
||||
const queryString = data.query;
|
||||
const variablesString = data.variables
|
||||
? JSON.stringify(data.variables, null, 2)
|
||||
: null;
|
||||
const resultString = data.result
|
||||
? JSON.stringify(data.result, null, 2)
|
||||
: null;
|
||||
const operationName = data.operationName;
|
||||
|
||||
return `<!--
|
||||
The request to this GraphQL server provided the header "Accept: text/html"
|
||||
and as a result has been presented GraphiQL - an in-browser IDE for
|
||||
exploring GraphQL.
|
||||
|
||||
If you wish to receive JSON, provide the header "Accept: application/json" or
|
||||
add "&raw" to the end of the URL within a browser.
|
||||
-->
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>GraphiQL</title>
|
||||
<meta name="robots" content="noindex" />
|
||||
<meta name="referrer" content="origin">
|
||||
<style>
|
||||
body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
}
|
||||
#graphiql {
|
||||
height: 100vh;
|
||||
}
|
||||
</style>
|
||||
<link href="//cdn.jsdelivr.net/npm/graphiql@${GRAPHIQL_VERSION}/graphiql.css" rel="stylesheet" />
|
||||
<script src="//cdn.jsdelivr.net/es6-promise/4.0.5/es6-promise.auto.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/fetch/0.9.0/fetch.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/react/15.4.2/react.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/react/15.4.2/react-dom.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/graphiql@${GRAPHIQL_VERSION}/graphiql.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="graphiql">Loading...</div>
|
||||
<script>
|
||||
// Collect the URL parameters
|
||||
var parameters = {};
|
||||
window.location.search.substr(1).split('&').forEach(function (entry) {
|
||||
var eq = entry.indexOf('=');
|
||||
if (eq >= 0) {
|
||||
parameters[decodeURIComponent(entry.slice(0, eq))] =
|
||||
decodeURIComponent(entry.slice(eq + 1));
|
||||
}
|
||||
});
|
||||
|
||||
// Produce a Location query string from a parameter object.
|
||||
function locationQuery(params) {
|
||||
return '?' + Object.keys(params).filter(function (key) {
|
||||
return Boolean(params[key]);
|
||||
}).map(function (key) {
|
||||
return encodeURIComponent(key) + '=' +
|
||||
encodeURIComponent(params[key]);
|
||||
}).join('&');
|
||||
}
|
||||
|
||||
// Derive a fetch URL from the current URL, sans the GraphQL parameters.
|
||||
var graphqlParamNames = {
|
||||
query: true,
|
||||
variables: true,
|
||||
operationName: true
|
||||
};
|
||||
|
||||
var otherParams = {};
|
||||
for (var k in parameters) {
|
||||
if (parameters.hasOwnProperty(k) && graphqlParamNames[k] !== true) {
|
||||
otherParams[k] = parameters[k];
|
||||
}
|
||||
}
|
||||
var fetchURL = locationQuery(otherParams);
|
||||
|
||||
// Defines a GraphQL fetcher using the fetch API.
|
||||
function graphQLFetcher(graphQLParams) {
|
||||
return fetch(fetchURL, {
|
||||
method: 'post',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(graphQLParams),
|
||||
credentials: 'include',
|
||||
}).then(function (response) {
|
||||
return response.text();
|
||||
}).then(function (responseBody) {
|
||||
try {
|
||||
return JSON.parse(responseBody);
|
||||
} catch (error) {
|
||||
return responseBody;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// When the query and variables string is edited, update the URL bar so
|
||||
// that it can be easily shared.
|
||||
function onEditQuery(newQuery) {
|
||||
parameters.query = newQuery;
|
||||
updateURL();
|
||||
}
|
||||
|
||||
function onEditVariables(newVariables) {
|
||||
parameters.variables = newVariables;
|
||||
updateURL();
|
||||
}
|
||||
|
||||
function onEditOperationName(newOperationName) {
|
||||
parameters.operationName = newOperationName;
|
||||
updateURL();
|
||||
}
|
||||
|
||||
function updateURL() {
|
||||
history.replaceState(null, null, locationQuery(parameters));
|
||||
}
|
||||
|
||||
// Render <GraphiQL /> into the body.
|
||||
ReactDOM.render(
|
||||
React.createElement(GraphiQL, {
|
||||
fetcher: graphQLFetcher,
|
||||
onEditQuery: onEditQuery,
|
||||
onEditVariables: onEditVariables,
|
||||
onEditOperationName: onEditOperationName,
|
||||
query: ${safeSerialize(queryString)},
|
||||
response: ${safeSerialize(resultString)},
|
||||
variables: ${safeSerialize(variablesString)},
|
||||
operationName: ${safeSerialize(operationName)},
|
||||
}),
|
||||
document.getElementById('graphiql')
|
||||
);
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
Reference in new issue
Block a user