Skip to content

Instantly share code, notes, and snippets.

@boldijar
Created January 27, 2017 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boldijar/46396489ea5ea44fa5c3ebf66fc0d03e to your computer and use it in GitHub Desktop.
Save boldijar/46396489ea5ea44fa5c3ebf66fc0d03e to your computer and use it in GitHub Desktop.
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