- Building Enterprise JavaScript Applications
- Daniel Li
- 358字
- 2021-07-23 16:31:25
Run E2E test
But if we run our E2E tests now, the scenario that sends a malformed JSON would fail. This is because of how the body-parser middleware works. The bodyParser.json() middleware will attempt to parse the payload of all requests that has their Content-Type header set to application/json. However, if the payload itself is not a valid JSON object, the middleware will throw an error similar to the following:
SyntaxError {
expose: true,
statusCode: 400,
status: 400,
body: '{"email": "dan@danyll.com", name: }',
type: 'entity.parse.failed'
}
Therefore, we need to catch this error in order to provide the correct response. Error handling can also be done through middleware, but they must be defined at the end, after other middleware. In the error handler middleware, we need to check whether the error thrown is caused by a malformed JSON payload, and if it is, send the 'Payload should be in JSON format' response we defined earlier.
Try your hands on implementing this error handler middleware; when you finish, compare your src/index.js file with the following one:
import '@babel/polyfill';
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json({ limit: 1e6 }));
app.post('/users', (req, res) => {
if (req.headers['content-length'] === '0') {
res.status(400);
res.set('Content-Type', 'application/json');
res.json({
message: 'Payload should not be empty',
});
return;
}
if (req.headers['content-type'] !== 'application/json') {
res.status(415);
res.set('Content-Type', 'application/json');
res.json({
message: 'The "Content-Type" header must always be "application/json"',
});
}
});
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && 'body' in err && err.type === 'entity.parse.failed') {
res.status(400);
res.set('Content-Type', 'application/json');
res.json({ message: 'Payload should be in JSON format' });
return;
}
next();
});
app.listen(process.env.SERVER_PORT, () => {
// eslint-disable-next-line no-console
console.log(`Hobnob API server listening on port ${process.env.SERVER_PORT}!`);
});
Now, when we run our E2E tests, they should all be passing:
$ yarn run test:e2e
..................
3 scenarios (3 passed)
18 steps (18 passed)
We have now successfully migrated our API to Express, and thus completed our (long) refactoring step. Let's commit our hard work into the Git repository:
$ git add -A
$ git commit -m "Migrate API to Express"