Skip to content

Instantly share code, notes, and snippets.

@aseemk
Created February 18, 2013 18:00
Show Gist options
  • Save aseemk/4979283 to your computer and use it in GitHub Desktop.
Save aseemk/4979283 to your computer and use it in GitHub Desktop.
A simple message-tracking web server.
express = require 'express'
app = express()
# the list of all messages we've received:
messages = []
# a map from all the clients we've seen (by their IDs),
# to their next unseen messages (by the messages' indices):
clients = {}
# since clients will be sending us messages:
app.use express.bodyParser()
# for debugging, GET / returns our internal state:
app.get '/', (req, res) ->
res.send {messages, clients}
# GET /messages returns the latest messages for this client:
app.get '/messages', (req, res) ->
# TODO how do you identify clients? assuming header for now:
id = req.header['x-client-id'] or 'anonymous'
# what's the next unseen message for this client?
index = clients[id] or 0
# return that message and the rest since...
res.send messages[index...]
# ...and remember the next unseen index for this client now:
clients[id] = messages.length
# POST /messages lets clients add a new message:
app.post '/messages', (req, res) ->
# TODO any validation? security? assuming body has been parsed:
messages.push req.body
# signal some success:
res.send 204
app.listen 8000
console.log 'Listening on port 8000...'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment