-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.js
53 lines (41 loc) · 1.65 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const http = require('http');
const bodyParser = require('body-parser'); // eslint-disable-line import/no-extraneous-dependencies
const express = require('express'); // eslint-disable-line import/no-extraneous-dependencies
const ERA = require('./index');
const ERAMemory = require('./storage/ERAMemory');
// Initialize ERA with in-memory storage.
const era = new ERA(new ERAMemory());
// Initialize Express.
const app = express();
// Logger.
app.use((request, response, next) => {
console.log(new Date(), request.method, request.path); // eslint-disable-line no-console
next();
});
// express-route-audit middleware; counts routed requests.
app.use((...args) => era.middleware(...args));
// Router.
const router = new express.Router({});
router.route('/ping').get((request, response) => response.send('PONG'));
router.route('/hello/:target').get((request, response) => response.send(request.params.target));
app.use(router);
// No router; POST method.
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/hello', (request, response) => response.send(request.body));
// Report on route usage.
app.get('/report', (request, response, next) => era.report(app)
.then(report => response.json(report))
.catch(error => next(error)));
// Clear report.
app.delete('/report', (request, response, next) => era.storage.clear()
.then(() => response.sendStatus(204))
.catch(error => next(error)));
// 404
app.use((request, response) => response.sendStatus(404));
// Start server.
const server = http.createServer(app);
const port = 3000;
server.listen(port);
server.on('listening', () => {
console.log(`listening on ${port}`); // eslint-disable-line no-console
});