Skip to content

Instantly share code, notes, and snippets.

@Ficik
Last active December 15, 2015 08:39
Show Gist options
  • Select an option

  • Save Ficik/5232332 to your computer and use it in GitHub Desktop.

Select an option

Save Ficik/5232332 to your computer and use it in GitHub Desktop.
w20-cv5
http = require "http"
crypto = require "crypto"
hash = (text) -> crypto.createHash("md5").update(text).digest("hex")
all = (array, fn) ->
for value in array
return false unless fn(value)
return true
any = (array, fn) ->
for value in array
return true if fn(value)
return false
DB =
customers : []
addCustomer : (name) ->
DB.customers.push
id : DB.customers.length
name : name
modified : new Date().getTime()
orders : []
DB.addCustomer "aaa"
DB.addCustomer "bbb"
server = http.createServer (req, res) ->
res.setHeader 'Content-Type', 'application/json'
if req.url == "/customers"
strong = "\""+(hash(JSON.stringify DB.customers))+"\""
weak = "\"W/"+(hash JSON.stringify (DB.customers.map (x) -> {id : x.id, name: x.name}))+"\""
res.setHeader "ETag", strong+", "+weak
if (!!(etags = req.headers["if-none-match"]) and any (etags.split(",").map (x) -> x.trim()), (x)-> x == strong or x == weak) or
(!!(date = req.headers["if-modified-since"]) and !!(date = Date.parse(date)) and (all DB.customers, (x) -> x.modified <= date ))
res.statusCode = 304
res.end()
return
res.write JSON.stringify DB.customers
res.end()
server.listen 8080
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment