Express Response Times Example

In this example we’ll create a server which has an index page that prints out ‘hello world’, and a page

http://localhost:3000/times which prints out the last ten response times that influxDB gave us.

The end result should look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
curl -s localhost:3000
Hello world

curl -s localhost:3000/times | jq
[
{
"time": "2016-10-09T19:13:26.815Z",
"duration": 205,
"host": "ares.peet.io",
"path": "/"
}
]

Get started by installing and importing everything we need. This example requires Node 6.

1
npm install influx express

Now create a new file app.js and start writing

1
2
3
4
5
6
const Influx = require('../../')
const express = require('express')
const http = require('http')
const os = require('os')

const app = express()

Create a new influx client. We tell it to use the express_response_db database by default, and give it some information about the schema we’re writing. It can use this to be smarter about what data formats it writes and do some basic validation for us.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const influx = new Influx.InfluxBD({
host: 'localhost',
database: 'express_response_db',
schema: [
{
measurement: 'response_time',
fields: {
path: Influx.FieldType.STRING,
duration: Influx.FieldType.INTEGER
},
tags: [
'host'
]
}
]
})

Now we have a working influx client!

We’ll make sure the database exists and boot the app.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
influx.getDatabaseName()
.then(names => {
if (!names.includes('express_response_db')) {
return influx.createDatabase('express_response_db')
}
})
.then(() => {
http.createServer(app).listen(3000, () => {
console.log('Listening on port 3000')
})
})
.catch(err => {
console.error('Error creating Influx database')
})

Finally we’ll define the middleware and routes we’ll use. We have a generic middleware that records the time between when requests comes in, and the time we response to them. We also have another route called /times which prints out the last ten timings we recorded.

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
app.use((req, res, next) => {
const start = Date.now()
res.on('finish', () => {
const duration = Date.now() - start
console.log(`Request to ${req.path} took ${duration} ms`)
influx.writePoints([
{
measurement: 'response_times',
tags: { host: os.hostname() },
fields: { duration, path: req.path }
}
]).catch(err => {
console.log(`Error saving data to InfluxDB: ${err.stack}`)
})
})
return next()
})

app.get('/', (req, res) => {
setTimeout(() => res.end('Hello world'), Math.random() * 500)
})

app.get('/times', (req, res) => {
influx.query(`
select * from response_times
where host = ${Influx.escape.stringLit(os.hostname())}
order by time desc
limit 10
`).then(result => {
res.json(result)
}).catch(err => {
res.status(500).send(err.stack)
})
})