-
Notifications
You must be signed in to change notification settings - Fork 33
/
index.js
67 lines (50 loc) · 1.5 KB
/
index.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
const stream = require('stream')
const Router = require('router')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const debug = require('debug')('dss')
const router = Router()
router.__dataStore = {}
const morganDebugStream = new stream.Writable({
write: function (chunk, encoding, done) {
// strip newlines (to avoid extra empty log items in the 'tiny' morgan protocol)
const chunkData = chunk.toString().replace(/[\n\r]/g, '')
if (chunkData.length > 0) {
debug(chunkData)
}
done()
}
})
router.use(morgan('tiny', { stream: morganDebugStream }))
router.param('id', (req, res, next, id) => {
req.params = {
id
}
next()
})
// parse all bodies up to 10mb regardless of mime type as a buffer
router.use(bodyParser.raw({ limit: '10mb', type: () => true }))
const bodyDebug = debug.extend('body')
router.post('/data/:id', (req, res) => {
const deviceId = req.params.id
if (!router.__dataStore[deviceId]) {
router.__dataStore[deviceId] = []
}
// log the body, using the debug body instance
bodyDebug(req.body.toString())
router.__dataStore[deviceId].push(req.body)
res.statusCode = 200
res.end()
})
router.get('/data/:id', (req, res) => {
const deviceId = req.params.id
if (!router.__dataStore[deviceId] || router.__dataStore[deviceId].length === 0) {
res.statusCode = 404
res.end()
} else {
const data = router.__dataStore[deviceId].shift()
res.statusCode = 200
res.end(data)
}
})
module.exports = router