Skip to content

Commit

Permalink
Init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nodkz committed Apr 22, 2016
0 parents commit f81556a
Show file tree
Hide file tree
Showing 22 changed files with 616 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -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"]
}
}
}
4 changes: 4 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "airbnb",
"parser": "babel-eslint"
}
37 changes: 37 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.DS_Store
*.log
src
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Pavel Chertorogov <[email protected]>
9 changes: 9 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -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.
Empty file added README.md
Empty file.
67 changes: 67 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
38 changes: 38 additions & 0 deletions src/express-middleware/graphqlBatchHTTPWrapper.js
Original file line number Diff line number Diff line change
@@ -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();
}
);
};
}
54 changes: 54 additions & 0 deletions src/fetchWrapper.js
Original file line number Diff line number Diff line change
@@ -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;
}
28 changes: 28 additions & 0 deletions src/formatRequestErrors.js
Original file line number Diff line number Diff line change
@@ -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');
}
15 changes: 15 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -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,
};
43 changes: 43 additions & 0 deletions src/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -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;
});
};
}
31 changes: 31 additions & 0 deletions src/middleware/logger.js
Original file line number Diff line number Diff line change
@@ -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;
});
};
}
18 changes: 18 additions & 0 deletions src/middleware/perf.js
Original file line number Diff line number Diff line change
@@ -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;
});
};
}
Loading

0 comments on commit f81556a

Please sign in to comment.