Skip to content

Instantly share code, notes, and snippets.

@Ficik
Created March 19, 2013 06:44
Show Gist options
  • Select an option

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

Select an option

Save Ficik/5194162 to your computer and use it in GitHub Desktop.
w20-cv3
storage =
books:
1:
"name" : "Nazev"
"isbn" : "123556"
"publisher" : "/publisher/1"
"author" : "/author/2"
2:
"name" : "Nazev"
"isbn" : "123556"
"publisher" : "/publisher/1"
"author" : "/author/1"
publisher:
1:
"name" : "Publisher Name"
"country" : "Country"
"books" : "/books?publisher=1"
author:
2:
"name" : "author name"
"books" : "/books?author=2"
http = require "http"
server = http.createServer (req, res) ->
res.setHeader 'Content-Type', "application/json"
req.data = ""
req.on "data", (data)->
req.data += data
req.on "end", ()->
if req.url.match /^\/books\/?$/
return unless methodRequired req, res, ["GET", "POST"]
if req.method == "POST"
id = 0
while (id = Math.ceil Math.random()*1000) of storage.books
pass
storage.books[id] = JSON.parse req.data
res.setHeader "Location", "/books/"+id
if req.method == "GET"
res.write JSON.stringify ({
name: book.name
detail : "/books/"+id
} for id, book of storage.books)
else if match = req.url.match /^\/books\/?\?author=([0-9]+)$/
return unless methodRequired req, res, ["GET"]
author_id = match[1]
res.write JSON.stringify ({
name: book.name
detail : "/books/"+id
} for id, book of storage.books when book.author == "/author/"+author_id)
else if match = req.url.match /^\/books\/?\?publisher=([0-9]+)$/
return unless methodRequired req, res, ["GET"]
publisher_id = match[1]
res.write JSON.stringify ({
name: book.name
detail : "/books/"+id
} for id, book of storage.books when book.publisher == "/publisher/"+publisher_id)
else if match = req.url.match /^\/books\/([0-9]+)$/
return unless methodRequired req, res, ["GET"]
id = match[1]
if id of storage.books
res.write JSON.stringify storage.books[id]
else
res.statusCode = 404
else if match = req.url.match /^\/publisher\/([0-9]+)$/
return unless methodRequired req, res, ["GET"]
id = match[1]
if id of storage.publisher
res.write JSON.stringify storage.publisher[id]
else
res.statusCode = 404
else if match = req.url.match /^\/author\/([0-9]+)$/
return unless methodRequired req, res, ["GET"]
id = match[1]
if id of storage.author
res.write JSON.stringify storage.author[id]
else
res.statusCode = 404
else
res.writeHead 400
res.end()
return
methodRequired = (req, res, methods) ->
if req.method not in methods
res.writeHead 405
return false
return true
server.listen 8080
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment