Created
January 27, 2017 08:11
-
-
Save boldijar/46396489ea5ea44fa5c3ebf66fc0d03e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Koa = require('koa'); | |
const app = new Koa(); | |
const server = require('http').createServer(app.callback()); | |
const WebSocket = require('ws'); | |
const wss = new WebSocket.Server({server}); | |
const Router = require('koa-router'); | |
const cors = require('koa-cors'); | |
const bodyparser = require('koa-bodyparser'); | |
app.use(bodyparser()); | |
app.use(cors()); | |
const router = new Router(); | |
router.get('/note', ctx => { | |
const clientLastUpdated = parseInt(ctx.request.query.lastUpdated); | |
ctx.response.body = notes | |
.filter(n => clientLastUpdated ? n.updated > clientLastUpdated: true) | |
.sort((n1, n2) => -(n1.updated - n2.updated)); | |
ctx.response.status = 200; | |
}); | |
router.put('/note/:id', ctx => { | |
const note = ctx.request.body; | |
const id = ctx.params.id; | |
const index = notes.findIndex(n => n.id === id); | |
if (id !== note.id || index === -1) { | |
ctx.response.body = {text: 'Note not found'}; | |
ctx.response.status = 400; | |
} else if (note.version < notes[index].version) { | |
ctx.response.body = notes[index]; | |
ctx.response.status = 409; | |
} else { | |
lastUpdated = note.updated = Date.now(); | |
note.version++; | |
notes[index] = note; | |
ctx.response.body = note; | |
ctx.response.status = 200; | |
broadcast(note); | |
} | |
}); | |
app.use(router.routes()); | |
app.use(router.allowedMethods()); | |
server.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment