Commit 0c2a5cf8 authored by A. Koch's avatar A. Koch

refactoring, updates

parent 9fa35605
This diff is collapsed.
const
http = require('http'),
polka = require('polka'),
Primus = require('primus'),
winston = require('winston')
{ json } = require('body-parser'),
Primus = require('primus')
/**
* HTTP server
*/
const
port = process.env.PORT || 3030,
host = process.env.HOST || '0.0.0.0',
server = http.createServer(),
primus = new Primus(server, { transformer: 'uws' }),
app = polka({ server })
{ PORT = 3030, HOST = '0.0.0.0' } = process.env,
server = http.createServer()
/**
* Logger
*/
const winston = require('winston')
winston.level = process.env.NODE_ENV === 'production' ? 'error' : 'info'
winston.level = process.env.LOG_LEVEL || winston.level
/**
* Set up WebSockets (Primus)
*/
const primus = new Primus(server, { transformer: 'uws' })
primus.on('connection', spark => {
winston.log('debug', `Spark ${spark.id} connected with address ${spark.address}`)
})
......@@ -22,9 +31,22 @@ primus.on('disconnection', spark => {
winston.log('debug', `Spark ${spark.id} disconnected with address ${spark.address}`)
})
app.get('/annotations.json', (req, res) => {
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ test: 'asdf' }))
})
/**
* Setup API server (Polka)
*/
const
Service = require('./service'),
app = polka({ server })
app.use(json())
/**
* Configure resources
*/
const annotations = new Service('annotations', app)
annotations.on('message', message => primus.write(message))
app.listen(port, host).then(() => winston.log('info', `API started on ${host}:${port}`))
/**
* Start server
*/
app.listen(PORT, HOST).then(() => winston.log('info', `API started on ${HOST}:${PORT}`))
const
send = require('@polka/send-type'),
TinyEmitter = require('tiny-emitter')
class Service extends TinyEmitter {
constructor (name, app) {
super()
this._name = name
const _this = this
app.get(`/${this._name}.json`, (req, res) => {
_this._response(req, res, [{ hello: 'world' }])
})
app.get(`/${this._name}/:id.json`, (req, res) => {
_this._response(req, res, { hello: 'world' })
})
app.post(`/${this._name}.json`, (req, res) => {
const data = req.body
_this._response(req, res, data)
})
app.put(`/${this._name}/:id.json`, (req, res) => {
const data = req.body
_this._response(req, res, data)
})
app.patch(`/${this._name}/:id.json`, (req, res) => {
const data = req.body
_this._response(req, res, data)
})
app.delete(`/${this._name}/:id.json`, (req, res) => {
const data = req.body
_this._response(req, res, data)
})
}
_response (req, res, data = {}) {
this.emit('message', { method: req.method, id: data.id })
send(res, 200, data)
}
}
module.exports = Service
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment