-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathexpress-server.js
71 lines (59 loc) · 1.76 KB
/
express-server.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict';
const express = require('express');
const Prometheus = require('prom-client');
const bodyParser = require('body-parser');
const config = require('./config');
const app = express();
const middleware = require('../../../../src/index.js').expressMiddleware;
const router = require('./router');
const checkoutsTotal = Prometheus.register.getSingleMetric('checkouts_total') || new Prometheus.Counter({
name: 'checkouts_total',
help: 'Total number of checkouts',
labelNames: ['payment_method']
});
app.use(middleware({ useUniqueHistogramName: config.useUniqueHistogramName }));
app.use(bodyParser.json());
app.use((req, res, next) => {
if (req.headers.error) {
next(new Error('Error'));
}
next();
});
app.use('/v2', router);
app.get('/hello', (req, res, next) => {
setTimeout(() => {
res.json({ message: 'Hello World!' });
next();
}, Math.round(Math.random() * 200));
});
app.get('/hello/:time', (req, res, next) => {
setTimeout(() => {
res.json({ message: 'Hello World!' });
next();
}, parseInt(req.param.time));
});
app.get('/bad', (req, res, next) => {
next(new Error('My Error'));
});
app.get('/checkout', (req, res, next) => {
const paymentMethod = Math.round(Math.random()) === 0 ? 'stripe' : 'paypal';
checkoutsTotal.inc({
payment_method: paymentMethod
});
res.json({ status: 'ok' });
next();
});
app.post('/test', (req, res, next) => {
setTimeout(() => {
res.status(201);
res.json({ message: 'Hello World!' });
next();
}, req.body.delay);
});
// Error handler
app.use((err, req, res, next) => {
res.statusCode = 500;
// Do not expose your error in production
res.json({ error: err.message });
});
module.exports = app;