Last active
December 15, 2015 08:39
-
-
Save Ficik/5232332 to your computer and use it in GitHub Desktop.
w20-cv5
This file contains hidden or 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
| 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