Skip to content

Commit

Permalink
style: fix eslint and prettier errors
Browse files Browse the repository at this point in the history
  • Loading branch information
nodkz committed Nov 2, 2017
1 parent 7fd0cc4 commit 6333dad
Show file tree
Hide file tree
Showing 13 changed files with 216 additions and 241 deletions.
24 changes: 12 additions & 12 deletions src/createRequestError.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,18 @@ function formatRequestErrors(request, errors) {
// 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')
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;
})
Expand Down
2 changes: 1 addition & 1 deletion src/fetchWithMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* eslint-disable no-param-reassign */
/* eslint-disable no-param-reassign, prefer-const */

import createRequestError from './createRequestError';

Expand Down
3 changes: 1 addition & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import perfMiddleware from './middleware/perf';
import loggerMiddleware from './middleware/logger';
import gqErrorsMiddleware from './middleware/gqErrors';
import deferMiddleware from './middleware/defer';
import graphqlBatchHTTPWrapper
from './express-middleware/graphqlBatchHTTPWrapper';
import graphqlBatchHTTPWrapper from './express-middleware/graphqlBatchHTTPWrapper';

export {
RelayNetworkLayer,
Expand Down
91 changes: 44 additions & 47 deletions src/middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,56 +21,53 @@ 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'));
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}`;
}
resolve(token);
return next(req);
})
.then(token => {
if (token) {
req.headers[header] = `${prefix}${token}`;
}
return next(req);
})
.catch(err => {
if (
err &&
err.fetchResponse &&
err.fetchResponse.status === 401 &&
tokenRefreshPromise
) {
throw new WrongTokenError(
'Received status 401 from server',
err.fetchResponse
);
} else {
throw err;
}
})
.catch(err => {
if (err.name === 'WrongTokenError') {
if (!tokenRefreshInProgress) {
tokenRefreshInProgress = Promise.resolve(
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
.catch(err => {
if (
err &&
err.fetchResponse &&
err.fetchResponse.status === 401 &&
tokenRefreshPromise
) {
throw new WrongTokenError(
'Received status 401 from server',
err.fetchResponse
);
} else {
throw err;
}
})
.catch(err => {
if (err.name === 'WrongTokenError') {
if (!tokenRefreshInProgress) {
tokenRefreshInProgress = Promise.resolve(
tokenRefreshPromise(req, err.res)
).then(newToken => {
tokenRefreshInProgress = null;
return newToken;
});
}

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

throw err;
});
};
}
54 changes: 25 additions & 29 deletions src/middleware/batch.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,23 @@ export default function batchMiddleware(opts = {}) {
const maxBatchSize = opts.maxBatchSize || DEFAULT_BATCH_SIZE;
const singleton = {};

return next =>
req => {
// never batch mutations with files
// mutation without files can be batched if allowMutations = true
if (
req.relayReqType === 'mutation' &&
(!allowMutations || (global.FormData && req.body instanceof FormData))
) {
return next(req);
}

return passThroughBatch(req, next, {
batchTimeout,
batchUrl,
singleton,
maxBatchSize,
});
};
return next => req => {
// never batch mutations with files
// mutation without files can be batched if allowMutations = true
if (
req.relayReqType === 'mutation' &&
(!allowMutations || (global.FormData && req.body instanceof FormData))
) {
return next(req);
}

return passThroughBatch(req, next, {
batchTimeout,
batchUrl,
singleton,
maxBatchSize,
});
};
}

function passThroughBatch(req, next, opts) {
Expand All @@ -48,8 +47,8 @@ function passThroughBatch(req, next, opts) {

// queue request
return new Promise((resolve, reject) => {
const relayReqId = req.relayReqId;
const requestMap = singleton.batcher.requestMap;
const { relayReqId } = req;
const { requestMap } = singleton.batcher;
requestMap[relayReqId] = requestMap[relayReqId] || [];
requestMap[relayReqId].push({
req,
Expand All @@ -72,15 +71,12 @@ function prepareNewBatcher(next, opts) {
acceptRequests: true,
};

setTimeout(
() => {
batcher.acceptRequests = false;
sendRequests(batcher.requestMap, next, opts)
.then(() => finalizeUncompleted(batcher))
.catch(() => finalizeUncompleted(batcher));
},
opts.batchTimeout
);
setTimeout(() => {
batcher.acceptRequests = false;
sendRequests(batcher.requestMap, next, opts)
.then(() => finalizeUncompleted(batcher))
.catch(() => finalizeUncompleted(batcher));
}, opts.batchTimeout);

return batcher;
}
Expand Down
33 changes: 16 additions & 17 deletions src/middleware/gqErrors.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,24 @@ export default function gqErrorsMiddleware(opts = {}) {
});
}

return next =>
req => {
const query = `${req.relayReqType} ${req.relayReqId}`;
return next => req => {
const query = `${req.relayReqType} ${req.relayReqId}`;

return next(req).then(res => {
if (res.json) {
if (Array.isArray(res.json)) {
res.json.forEach(batchItem => {
if (batchItem.payload.errors) {
displayErrors(batchItem.payload.errors, { query, req, res });
}
});
} else if (res.json.errors) {
displayErrors(res.json.errors, { query, req, res });
}
return next(req).then(res => {
if (res.json) {
if (Array.isArray(res.json)) {
res.json.forEach(batchItem => {
if (batchItem.payload.errors) {
displayErrors(batchItem.payload.errors, { query, req, res });
}
});
} else if (res.json.errors) {
displayErrors(res.json.errors, { query, req, res });
}
return res;
});
};
}
return res;
});
};
}

function noticeAbsentStack() {
Expand Down
37 changes: 18 additions & 19 deletions src/middleware/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,21 @@
export default function loggerMiddleware(opts = {}) {
const logger = opts.logger || console.log.bind(console, '[RELAY-NETWORK]');

return next =>
req => {
const query = `${req.relayReqType} ${req.relayReqId}`;
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
);
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.
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';
Expand All @@ -29,10 +28,10 @@ export default function loggerMiddleware(opts = {}) {
app.use('/graphql/batch', bodyParser.json(), graphqlBatchHTTPWrapper(graphQLMiddleware));
app.use('/graphql', graphQLMiddleware);
`
);
}
);
}
return res;
});
};
}
return res;
});
};
}
21 changes: 10 additions & 11 deletions src/middleware/perf.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@
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}`;
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();
const start = new Date().getTime();

return next(req).then(res => {
const end = new Date().getTime();
logger(`${query}: ${end - start}ms`);
return res;
});
};
return next(req).then(res => {
const end = new Date().getTime();
logger(`${query}: ${end - start}ms`);
return res;
});
};
}
Loading

0 comments on commit 6333dad

Please sign in to comment.