-
Notifications
You must be signed in to change notification settings - Fork 22
/
express.js
134 lines (124 loc) · 2.67 KB
/
express.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
'use strict';
const express = require('express');
const app = express();
const Influx = require('..');
const _ = require('lodash');
const client = new Influx('http://red:8086/mydb');
const onHeaders = require('on-headers');
// set the http stats schema
client.schema('http', {
use: 'integer',
code: 'integer',
bytes: 'integer',
url: 'string',
});
client.on('writeQueue', () => {
// sync write queue if the length is 100
if (client.writeQueueLength === 100) {
client.syncWrite()
.then(() => {
console.info('sync write success');
})
.catch(console.error);
}
});
function httpStats(req, res, next) {
const start = Date.now();
onHeaders(res, () => {
const code = res.statusCode;
const use = Date.now() - start;
const method = req.method;
const bytes = parseInt(res.get('Content-Length') || 0, 10);
const tags = {
spdy: _.sortedIndex([100, 300, 1000, 3000], use),
type: code / 100 | 0,
method,
};
const fields = {
use,
code,
bytes,
url: req.url,
route: req.route.path
};
// use queue for better performance
client.write('http')
.tag(tags)
.field(fields)
.queue();
});
next();
}
client.createDatabase().catch(err => {
console.error('create database fail err:', err);
});
app.use(httpStats);
app.use((req, res, next) => {
setTimeout(next, _.random(0, 5000));
});
app.get('/users/me', (req, res) => {
res.json({
account: 'vicanso',
name: 'Tree Xie',
});
});
app.get('/book/:id', (req, res) => {
const {
id,
} = req.params;
res.json({
id: id,
name: 'my book',
author: 'vicanso',
});
});
app.get('/order/:id', (req, res) => {
const code = _.sample([200, 304, 400, 403]);
switch (code) {
case 304:
res.status(304).send('');
break;
case 400:
res.status(400).json({
error: 'The id is not valid',
});
break;
case 403:
res.status(403).json({
error: 'Please login first',
});
break;
default:
res.json({
account: 'vicanso',
});
break;
}
});
app.get('/author/:id', (req, res) => {
const code = _.sample([200, 304, 500]);
switch (code) {
case 304:
res.status(304).send('');
break;
case 500:
res.status(500).json({
error: 'The database is disconnected',
});
break;
default:
res.json({
account: 'vicanso',
});
break;
}
});
let server;
const finish = () => {
console.info(`listen on http://127.0.0.1:${server.address().port}/`);
};
if (process.env.PORT) {
server = app.listen(process.env.PORT, finish);
} else {
server = app.listen(finish);
}