Skip to content

Commit

Permalink
style(Prettier): Add Prettier to eslint rules. Some other cleanups.
Browse files Browse the repository at this point in the history
  • Loading branch information
nodkz committed Mar 12, 2017
1 parent 27f95d8 commit 963e746
Show file tree
Hide file tree
Showing 16 changed files with 422 additions and 257 deletions.
6 changes: 2 additions & 4 deletions .babelrc
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
"defaults"
]
},
"include": ["transform-es2015-classes"],
"debug": true,
"include": ["transform-es2015-classes"]
}]
]
},
Expand All @@ -24,8 +23,7 @@
"chrome": 52
},
"loose": true,
"modules": false,
"debug": true
"modules": false
}]
]
}
Expand Down
13 changes: 12 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
{
"extends": "airbnb-base",
"extends": [
"airbnb-base",
"prettier"
],
"plugins": [
"prettier"
],
"parser": "babel-eslint",
"rules": {
"no-underscore-dangle": 0,
Expand All @@ -15,6 +21,11 @@
"exports": "always-multiline",
"functions": "ignore",
}],
"prettier/prettier": ["error", {
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80
}],
"no-plusplus": 0
},
"env": {
Expand Down
12 changes: 8 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,21 @@
"babel-eslint": "^7.1.1",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-polyfill": "^6.23.0",
"babel-preset-env": "^1.2.0",
"babel-preset-env": "^1.2.1",
"babel-register": "^6.23.0",
"chai": "^3.5.0",
"chai-as-promised": "^6.0.0",
"cz-conventional-changelog": "^2.0.0",
"eslint": "^3.17.0",
"eslint": "^3.17.1",
"eslint-config-airbnb-base": "^11.1.1",
"eslint-config-prettier": "^1.5.0",
"eslint-module-utils": "^2.0.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-prettier": "^2.0.1",
"fetch-mock": "^5.9.4",
"mocha": "^3.1.1",
"nyc": "^10.1.2",
"prettier": "^0.22.0",
"rimraf": "^2.6.1",
"semantic-release": "^6.3.2"
},
Expand All @@ -71,8 +74,9 @@
"build-lib": "rimraf lib && BABEL_ENV=lib babel src -d lib",
"build-es": "rimraf es && BABEL_ENV=es babel src -d es",
"lint": "eslint src test *.js",
"coverage": "nyc npm run test",
"test": "npm run lint && BABEL_ENV=lib mocha --require test/mocha-bootload --compilers js:babel-register test/*.test.js",
"coverage": "nyc npm run test:all",
"test": "BABEL_ENV=lib mocha --require test/mocha-bootload --compilers js:babel-register test/*.test.js",
"test:all": "npm run lint && npm run test",
"semantic-release": "semantic-release pre && npm publish && semantic-release post"
}
}
98 changes: 57 additions & 41 deletions src/express-middleware/graphqlBatchHTTPWrapper.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,66 @@
export default function (graphqlHTTPMiddleware) {
export default function(graphqlHTTPMiddleware) {
return (req, res) => {
const subResponses = [];
return 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.statusCode = st; return this; },
set() { return this; },
send(payload) {
resolve({ status: this.statusCode, id: data.id, payload });
},
req.body.map(
data =>
new Promise(resolve => {
const subRequest = {
__proto__: req.__proto__, // eslint-disable-line
...req,
body: data,
};
const subResponse = {
status(st) {
this.statusCode = st;
return this;
},
set() {
return this;
},
send(payload) {
resolve({ status: this.statusCode, id: data.id, payload });
},

// support [email protected]
setHeader() { return this; },
header() {},
write(payload) { this.payload = payload; },
end(payload) {
// support [email protected]
if (payload) {
// support [email protected]
setHeader() {
return this;
},
header() {},
write(payload) {
this.payload = payload;
}
resolve({ status: this.statusCode, id: data.id, payload: this.payload });
},
};
subResponses.push(subResponse);
graphqlHTTPMiddleware(subRequest, subResponse);
})
},
end(payload) {
// support [email protected]
if (payload) {
this.payload = payload;
}
resolve({
status: this.statusCode,
id: data.id,
payload: this.payload,
});
},
};
subResponses.push(subResponse);
graphqlHTTPMiddleware(subRequest, subResponse);
})
)
).then(responses => {
let response = '';
responses.forEach(({ status, id, payload }, idx) => {
if (status) {
res.status(status);
}
const comma = responses.length - 1 > idx ? ',' : '';
response += `{ "id":"${id}", "payload":${payload} }${comma}`;
)
.then(responses => {
let response = '';
responses.forEach(({ status, id, payload }, idx) => {
if (status) {
res.status(status);
}
const comma = responses.length - 1 > idx ? ',' : '';
response += `{ "id":"${id}", "payload":${payload} }${comma}`;
});
res.set('Content-Type', 'application/json');
res.send(`[${response}]`);
})
.catch(err => {
res.status(500).send({ error: err.message });
});
res.set('Content-Type', 'application/json');
res.send(`[${response}]`);
}).catch(err => {
res.status(500).send({ error: err.message });
});
};
}
18 changes: 9 additions & 9 deletions src/fetchWrapper.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable no-param-reassign */

export default function fetchWrapper(reqFromRelay, middlewares) {
const fetchAfterAllWrappers = (req) => {
const fetchAfterAllWrappers = req => {
let { url, ...opts } = req;

if (!url) {
Expand All @@ -12,10 +12,10 @@ export default function fetchWrapper(reqFromRelay, middlewares) {
}
}

return fetch(url, opts)
.then(res =>
// sub-promise for combining `res` with parsed json
res.json()
return fetch(url, opts).then(res => {
// sub-promise for combining `res` with parsed json
return res
.json()
.then(json => {
res.json = json;
return res;
Expand All @@ -24,8 +24,8 @@ export default function fetchWrapper(reqFromRelay, middlewares) {
console.warn('error parsing response json', e); // eslint-disable-line no-console
res.json = {};
return res;
}),
);
});
});
};

const wrappedFetch = compose(...middlewares)(fetchAfterAllWrappers);
Expand All @@ -35,7 +35,6 @@ export default function fetchWrapper(reqFromRelay, middlewares) {
.then(res => res.json);
}


/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
Expand All @@ -52,7 +51,8 @@ function compose(...funcs) {
} else {
const last = funcs[funcs.length - 1];
const rest = funcs.slice(0, -1);
return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args));
return (...args) =>
rest.reduceRight((composed, f) => f(composed), last(...args));
}
}

Expand Down
39 changes: 23 additions & 16 deletions src/formatRequestErrors.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,28 @@ export default function formatRequestErrors(request, errors) {
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);
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(Math.max(offset, 0))}^^^`,
].map(messageLine => indent + messageLine).join('\n');
}).join('\n')) :
'';
return prefix + message + locationMessage;
}).join('\n');
// 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(Math.max(offset, 0))}^^^`,
]
.map(messageLine => indent + messageLine)
.join('\n');
})
.join('\n')
: '';
return prefix + message + locationMessage;
})
.join('\n');
}
73 changes: 41 additions & 32 deletions src/middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,39 +21,48 @@ export default function authMiddleware(opts = {}) {

let tokenRefreshInProgress = null;

return next => req => {
return new Promise((resolve, reject) => {
const token = isFunction(tokenOrThunk) ? tokenOrThunk(req) : tokenOrThunk;
if (!token && tokenRefreshPromise && !allowEmptyToken) {
reject(new WrongTokenError('Token not provided, try fetch new one'));
}
resolve(token);
}).then(token => {
if (token) {
req.headers[header] = `${prefix}${token}`;
}
return next(req);
}).then(res => {
if (res.status === 401 && tokenRefreshPromise) {
throw new WrongTokenError('Received status 401 from server', res);
}
return res;
}).catch(err => {
if (err.name === 'WrongTokenError') {
if (!tokenRefreshInProgress) {
tokenRefreshInProgress = tokenRefreshPromise(req, err.res).then(newToken => {
tokenRefreshInProgress = null;
return newToken;
});
return next =>
req => {
return new Promise((resolve, reject) => {
const token = isFunction(tokenOrThunk)
? tokenOrThunk(req)
: tokenOrThunk;
if (!token && tokenRefreshPromise && !allowEmptyToken) {
reject(new WrongTokenError('Token not provided, try fetch new one'));
}
resolve(token);
})
.then(token => {
if (token) {
req.headers[header] = `${prefix}${token}`;
}
return next(req);
})
.then(res => {
if (res.status === 401 && tokenRefreshPromise) {
throw new WrongTokenError('Received status 401 from server', res);
}
return res;
})
.catch(err => {
if (err.name === 'WrongTokenError') {
if (!tokenRefreshInProgress) {
tokenRefreshInProgress = tokenRefreshPromise(
req,
err.res
).then(newToken => {
tokenRefreshInProgress = null;
return newToken;
});
}

return tokenRefreshInProgress.then(newToken => {
req.headers[header] = `${prefix}${newToken}`;
return next(req); // re-run query with new token
});
}
return tokenRefreshInProgress.then(newToken => {
req.headers[header] = `${prefix}${newToken}`;
return next(req); // re-run query with new token
});
}

throw err;
});
};
throw err;
});
};
}
Loading

0 comments on commit 963e746

Please sign in to comment.