diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..2be2154 --- /dev/null +++ b/.babelrc @@ -0,0 +1,14 @@ +{ + "presets": ["react"], + "plugins": ["dev-expression", "transform-runtime"], + + "env": { + "cjs": { + "presets": ["es2015-loose", "stage-0"], + "plugins": ["add-module-exports"] + }, + "es": { + "presets": ["es2015-loose-native-modules", "stage-0"] + } + } +} \ No newline at end of file diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..bb38fe3 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,4 @@ +{ + "extends": "airbnb", + "parser": "babel-eslint" +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aeb67e3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +node_modules + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history + +# Transpiled code +/es +/lib \ No newline at end of file diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..3b5d49d --- /dev/null +++ b/.npmignore @@ -0,0 +1,3 @@ +.DS_Store +*.log +src \ No newline at end of file diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..c2c8279 --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +Pavel Chertorogov \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..afe7817 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2016-present Pavel Chertorogov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/package.json b/package.json new file mode 100644 index 0000000..b20a7fa --- /dev/null +++ b/package.json @@ -0,0 +1,67 @@ +{ + "name": "react-relay-network-layer", + "version": "0.12.2", + "description": "Network Layer for React Relay and Express (Batch Queries, AuthToken, Logging)", + "files": [ + "es", + "lib" + ], + "main": "lib/index.js", + "jsnext:main": "es/index.js", + "scripts": { + "build": "npm run build-cjs && npm run build-es", + "build-cjs": "rimraf lib && BABEL_ENV=cjs babel src -d lib", + "build-es": "rimraf es && BABEL_ENV=es babel src -d es", + "lint": "eslint src test *.js", + "prepublish": "npm run build", + "test": "npm run lint" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodkz/react-relay-network-layer.git" + }, + "keywords": [ + "relay", + "react", + "network layer", + "batch", + "express", + "jwt", + "auth token" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/nodkz/react-relay-network-layer/issues" + }, + "homepage": "https://github.com/nodkz/react-relay-network-layer#readme", + "dependencies": { + "babel-runtime": "^6.6.1" + }, + "peerDependencies": { + "react-relay": ">=0.7.0" + }, + "devDependencies": { + "babel-cli": "^6.7.7", + "babel-core": "^6.7.7", + "babel-eslint": "^6.0.3", + "babel-loader": "^6.2.4", + "babel-plugin-add-module-exports": "^0.1.2", + "babel-plugin-dev-expression": "^0.2.1", + "babel-plugin-transform-runtime": "^6.7.5", + "babel-polyfill": "^6.7.4", + "babel-preset-es2015": "^6.6.0", + "babel-preset-es2015-loose": "^7.0.0", + "babel-preset-es2015-loose-native-modules": "^1.0.0", + "babel-preset-react": "^6.5.0", + "babel-preset-stage-0": "^6.5.0", + "babel-register": "^6.7.2", + "babel-relay-plugin": "^0.8.0", + "eslint": "^2.8.0", + "eslint-config-airbnb": "^7.0.0", + "eslint-plugin-jsx-a11y": "^0.6.2", + "eslint-plugin-react": "^4.3.0", + "graphql": "^0.4.18", + "graphql-relay": "^0.3.6", + "rimraf": "^2.5.2" + } +} \ No newline at end of file diff --git a/src/express-middleware/graphqlBatchHTTPWrapper.js b/src/express-middleware/graphqlBatchHTTPWrapper.js new file mode 100644 index 0000000..23263b9 --- /dev/null +++ b/src/express-middleware/graphqlBatchHTTPWrapper.js @@ -0,0 +1,38 @@ +export default function (graphqlHTTPMiddleware) { + return (req, res, next) => { + const subResponses = []; + Promise.all( + req.body.map(data => + new Promise((resolve) => { + const subRequest = { + __proto__: req.__proto__, // eslint-disable-line + ...req, + body: data, + }; + const subResponse = { + status(st) { this._status = st; return this; }, + set() { return this; }, + send(payload) { + resolve({ status: this._status, id: data.id, payload }); + }, + }; + subResponses.push(subResponse); + graphqlHTTPMiddleware(subRequest, subResponse); + }) + ) + ).then( + (responses) => { + const response = []; + responses.forEach(({ status, id, payload }) => { + if (status) { res.status(status); } + response.push({ + id, + payload: JSON.parse(payload), + }); + }); + res.send(response); + next(); + } + ); + }; +} diff --git a/src/fetchWrapper.js b/src/fetchWrapper.js new file mode 100644 index 0000000..bedc2c9 --- /dev/null +++ b/src/fetchWrapper.js @@ -0,0 +1,54 @@ +/* eslint-disable no-use-before-define, no-else-return, prefer-const */ + +import 'whatwg-fetch'; + +export default function fetchWrapper(reqFromRelay, middlewares) { + const fetchAfterAllWrappers = (req) => { + let { url, ...opts } = req; + + if (!url) { + if (req.relayReqType === 'batch-query') { + url = '/graphql/batch'; + } else { + url = '/graphql'; + } + } + + return fetch(url, opts).then(); + }; + + const wrappedFetch = compose(...middlewares)(fetchAfterAllWrappers); + + return wrappedFetch(reqFromRelay) + .then(throwOnServerError) + .then(response => response.json()); +} + + +/** + * Composes single-argument functions from right to left. The rightmost + * function can take multiple arguments as it provides the signature for + * the resulting composite function. + * + * @param {...Function} funcs The functions to compose. + * @returns {Function} A function obtained by composing the argument functions + * from right to left. For example, compose(f, g, h) is identical to doing + * (...args) => f(g(h(...args))). + */ +function compose(...funcs) { + if (funcs.length === 0) { + return arg => arg; + } else { + const last = funcs[funcs.length - 1]; + const rest = funcs.slice(0, -1); + return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args)); + } +} + +function throwOnServerError(response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + + throw response; +} diff --git a/src/formatRequestErrors.js b/src/formatRequestErrors.js new file mode 100644 index 0000000..70c1bd0 --- /dev/null +++ b/src/formatRequestErrors.js @@ -0,0 +1,28 @@ +/* eslint-disable prefer-template */ + +/** + * Formats an error response from GraphQL server request. + */ +export default function formatRequestErrors(request, errors) { + const CONTEXT_BEFORE = 20; + const CONTEXT_LENGTH = 60; + + const queryLines = request.getQueryString().split('\n'); + return errors.map(({ locations, message }, ii) => { + const prefix = `${ii + 1}. `; + const indent = ' '.repeat(prefix.length); + + // custom errors thrown in graphql-server may not have locations + const locationMessage = locations ? + ('\n' + locations.map(({ column, line }) => { + const queryLine = queryLines[line - 1]; + const offset = Math.min(column - 1, CONTEXT_BEFORE); + return [ + queryLine.substr(column - 1 - offset, CONTEXT_LENGTH), + `${' '.repeat(offset)}^^^`, + ].map(messageLine => indent + messageLine).join('\n'); + }).join('\n')) : + ''; + return prefix + message + locationMessage; + }).join('\n'); +} diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..519149d --- /dev/null +++ b/src/index.js @@ -0,0 +1,15 @@ +import RelayNetworkLayer from './relayNetworkLayer'; +import urlMiddleware from './middleware/url'; +import authMiddleware from './middleware/auth'; +import perfMiddleware from './middleware/perf'; +import loggerMiddleware from './middleware/logger'; +import graphqlBatchHTTPWrapper from './express-middleware/graphqlBatchHTTPWrapper'; + +export { + RelayNetworkLayer, + urlMiddleware, + authMiddleware, + perfMiddleware, + loggerMiddleware, + graphqlBatchHTTPWrapper, +}; diff --git a/src/middleware/auth.js b/src/middleware/auth.js new file mode 100644 index 0000000..1c588a7 --- /dev/null +++ b/src/middleware/auth.js @@ -0,0 +1,43 @@ +/* eslint-disable no-param-reassign, arrow-body-style */ + +import { isFunction } from '../utils'; + +class WrongTokenError extends Error { + constructor(msg, res = {}) { + super(msg); + this.res = res; + this.name = 'WrongTokenError'; + } +} + +export default function authMiddleware(opts = {}) { + const { token: tokenOrThunk, tokenRefreshPromise, prefix = 'Bearer ' } = opts; + + return next => req => { + return new Promise((resolve, reject) => { + const token = isFunction(tokenOrThunk) ? tokenOrThunk(req) : tokenOrThunk; + if (!token && tokenRefreshPromise) { + reject(new WrongTokenError('Token not provided, try fetch new one')); + } + resolve(token); + }).then(token => { + req.headers.Authorization = `${prefix}${token}`; + return next(req); + }).then(res => { + if (res.status === 401 && tokenRefreshPromise) { + throw new WrongTokenError('Was recieved status 401 from server', res); + } + return res; + }).catch(err => { + if (err.name === 'WrongTokenError') { + return tokenRefreshPromise(req, err.res) + .then(newToken => { + req.headers.Authorization = `${prefix}${newToken}`; + return next(req); // re-run query with new token + }); + } + + throw err; + }); + }; +} diff --git a/src/middleware/logger.js b/src/middleware/logger.js new file mode 100644 index 0000000..6aeac00 --- /dev/null +++ b/src/middleware/logger.js @@ -0,0 +1,31 @@ +/* eslint-disable no-console */ + +export default function perfMiddleware(opts = {}) { + const logger = opts.logger || console.log.bind(console, '[RELAY-NETWORK]'); + + return next => req => { + const query = `${req.relayReqType} ${req.relayReqId}`; + + logger(`Run ${query}`, req); + return next(req).then(res => { + if (res.status !== 200) { + logger(`Status ${res.status}: ${res.statusText} for ${query}`, req, res); + + if (res.status === 400 && req.relayReqType === 'batch-query') { + logger(`WARNING: You got 400 error for 'batch-query', probably problem on server side. + You should connect wrapper: + + import graphqlHTTP from 'express-graphql'; + import { graphqlBatchHTTPWrapper } from 'react-relay-network-layer'; + + const graphQLMiddleware = graphqlHTTP({ schema: GraphQLSchema }); + + app.use('/graphql/batch', bodyParser.json(), graphqlBatchHTTPWrapper(graphQLMiddleware)); + app.use('/graphql', graphQLMiddleware); + `); + } + } + return res; + }); + }; +} diff --git a/src/middleware/perf.js b/src/middleware/perf.js new file mode 100644 index 0000000..8b2b068 --- /dev/null +++ b/src/middleware/perf.js @@ -0,0 +1,18 @@ +/* eslint-disable no-console */ + +export default function performanceMiddleware(opts = {}) { + const logger = opts.logger || console.log.bind(console, '[RELAY-NETWORK]'); + + return next => req => { + // get query name here, because `req` can be changed after `next()` call + const query = `${req.relayReqType} ${req.relayReqId}`; + + const start = new Date().getTime(); + + return next(req).then(res => { + const end = new Date().getTime(); + logger(`${end - start}ms for ${query}`); + return res; + }); + }; +} diff --git a/src/middleware/url.js b/src/middleware/url.js new file mode 100644 index 0000000..99fd85f --- /dev/null +++ b/src/middleware/url.js @@ -0,0 +1,30 @@ +/* eslint-disable no-param-reassign */ + +import { isFunction } from '../utils'; + +export default function urlMiddleware(opts = {}) { + const urlOrThunk = opts.url || '/graphql'; + const batchUrlOrThunk = opts.batchUrl || '/graphql/batch'; + const fetchOpts = opts.opts; + + return next => req => { + if (fetchOpts) { + const { headers, ...otherOpts } = fetchOpts; + Object.assign(req, otherOpts); + if (headers) { + Object.assign(req.headers, headers); + } + } + + let url; + if (req.relayReqType === 'batch-query') { + url = batchUrlOrThunk; + } else { + url = urlOrThunk; + } + + req.url = isFunction(url) ? url(req) : url; + + return next(req); + }; +} diff --git a/src/relay/_query.js b/src/relay/_query.js new file mode 100644 index 0000000..03ff87f --- /dev/null +++ b/src/relay/_query.js @@ -0,0 +1,47 @@ +/* eslint-disable no-param-reassign, prefer-template */ + +import formatRequestErrors from '../formatRequestErrors'; + +export function queryPre(relayRequest) { + const req = { + relayReqId: relayRequest.getID(), + relayReqObj: relayRequest, + relayReqType: 'query', + method: 'POST', + headers: { + Accept: '*/*', + 'Content-Type': 'application/json', + }, + }; + + req.body = JSON.stringify({ + query: relayRequest.getQueryString(), + variables: relayRequest.getVariables(), + }); + + return req; +} + + +export function queryPost(relayRequest, fetchPromise) { + return fetchPromise.then(payload => { + if (payload.hasOwnProperty('errors')) { + const error = new Error( + 'Server request for query `' + relayRequest.getDebugName() + '` ' + + 'failed for the following reasons:\n\n' + + formatRequestErrors(relayRequest, payload.errors) + ); + error.source = payload; + relayRequest.reject(error); + } else if (!payload.hasOwnProperty('data')) { + relayRequest.reject(new Error( + 'Server response was missing for query `' + relayRequest.getDebugName() + + '`.' + )); + } else { + relayRequest.resolve({ response: payload.data }); + } + }).catch( + error => relayRequest.reject(error) + ); +} diff --git a/src/relay/mutation.js b/src/relay/mutation.js new file mode 100644 index 0000000..181561b --- /dev/null +++ b/src/relay/mutation.js @@ -0,0 +1,83 @@ +/* eslint-disable no-param-reassign, no-use-before-define, prefer-template */ + +import formatRequestErrors from '../formatRequestErrors'; + +export default function mutation(relayRequest, fetchWithMiddleware) { + const req = { + relayReqId: Date.now(), + relayReqObj: relayRequest, + relayReqType: 'mutation', + }; + + if (_hasFiles(relayRequest)) { + Object.assign(req, _mutationWithFiles(relayRequest)); + } else { + Object.assign(req, _mutation(relayRequest)); + } + + return fetchWithMiddleware(req) + .then(payload => { + if (payload.hasOwnProperty('errors')) { + const error = new Error( + 'Server request for mutation `' + relayRequest.getDebugName() + '` ' + + 'failed for the following reasons:\n\n' + + formatRequestErrors(relayRequest, payload.errors) + ); + error.source = payload; + relayRequest.reject(error); + } else { + relayRequest.resolve({ response: payload.data }); + } + }).catch( + error => relayRequest.reject(error) + ); +} + + +function _hasFiles(relayRequest) { + return !!(relayRequest.getFiles && relayRequest.getFiles()); +} + + +function _mutationWithFiles(relayRequest) { + const req = { + method: 'POST', + }; + + if (_hasFiles(relayRequest)) { + const files = relayRequest.getFiles(); + + if (!global.FormData) { + throw new Error('Uploading files without `FormData` not supported.'); + } + const formData = new FormData(); + formData.append('query', relayRequest.getQueryString()); + formData.append('variables', JSON.stringify(relayRequest.getVariables())); + for (const filename in files) { + if (files.hasOwnProperty(filename)) { + formData.append(filename, files[filename]); + } + } + req.body = formData; + } + + return req; +} + + +function _mutation(relayRequest) { + const req = { + method: 'POST', + headers: { + Accept: '*/*', + 'Content-Type': 'application/json', + }, + }; + + req.body = JSON.stringify({ + query: relayRequest.getQueryString(), + variables: relayRequest.getVariables(), + }); + + return req; +} diff --git a/src/relay/queries.js b/src/relay/queries.js new file mode 100644 index 0000000..5fc282b --- /dev/null +++ b/src/relay/queries.js @@ -0,0 +1,11 @@ +import { queryPre, queryPost } from './_query'; + +export default function queries(relayRequestList, fetchWithMiddleware) { + return Promise.all( + relayRequestList.map(relayRequest => { + const req = queryPre(relayRequest); + const fetchPromise = fetchWithMiddleware(req); + return queryPost(relayRequest, fetchPromise); + }) + ); +} diff --git a/src/relay/queriesBatch.js b/src/relay/queriesBatch.js new file mode 100644 index 0000000..ca11f74 --- /dev/null +++ b/src/relay/queriesBatch.js @@ -0,0 +1,41 @@ +import { queryPost } from './_query'; + +export default function queriesBatch(relayRequestList, fetchWithMiddleware) { + const requestMap = {}; + relayRequestList.forEach((req) => { + const reqId = req.getID(); + requestMap[reqId] = req; + }); + + const req = { + relayReqId: `BATCH_QUERY:${Object.keys(requestMap).join(':')}`, + relayReqObj: relayRequestList, + relayReqType: 'batch-query', + method: 'POST', + headers: { + Accept: '*/*', + 'Content-Type': 'application/json', + }, + }; + + req.body = JSON.stringify( + Object.keys(requestMap).map((id) => ({ + id, + query: requestMap[id].getQueryString(), + variables: requestMap[id].getVariables(), + })) + ); + + return fetchWithMiddleware(req) + .then(payloadList => { + payloadList.forEach(({ id, payload }) => { + const relayRequest = requestMap[id]; + if (relayRequest) { + queryPost( + relayRequest, + new Promise(resolve => {resolve(payload);}) + ); + } + }); + }); +} diff --git a/src/relayNetworkLayer.js b/src/relayNetworkLayer.js new file mode 100644 index 0000000..16e0ce8 --- /dev/null +++ b/src/relayNetworkLayer.js @@ -0,0 +1,39 @@ +/* eslint-disable arrow-body-style, no-unused-vars */ + +import queries from './relay/queries'; +import queriesBatch from './relay/queriesBatch'; +import mutation from './relay/mutation'; +import fetchWrapper from './fetchWrapper'; + + +export default class RelayNetworkLayer { + constructor(middlewares, options) { + this._options = options; + this._middlewares = Array.isArray(middlewares) ? middlewares : [middlewares]; + } + + supports = (...options) => { + // Does not support the only defined option, "defer". + return false; + }; + + sendQueries = (requests) => { + if (requests.length > 1 && !this._isBatchQueriesDisabled()) { + return queriesBatch(requests, this._fetchWithMiddleware); + } + + return queries(requests, this._fetchWithMiddleware); + }; + + sendMutation = (request) => { + return mutation(request, this._fetchWithMiddleware); + }; + + _fetchWithMiddleware = (req) => { + return fetchWrapper(req, this._middlewares); + }; + + _isBatchQueriesDisabled = () => { + return this._options && this._options.disableBatchQuery; + }; +} diff --git a/src/utils.js b/src/utils.js new file mode 100644 index 0000000..f4eb039 --- /dev/null +++ b/src/utils.js @@ -0,0 +1,3 @@ +export function isFunction(obj) { + return !!(obj && obj.constructor && obj.call && obj.apply); +}