Hacker News new | ask | show | jobs
by couchand 4412 days ago
As long as you're just working on JavaScript code for the front end, wouldn't it make sense to write this in node? That way you can avoid context switching. I'd daresay this would be much simpler in JavaScript as well, to the point that a tutorial isn't really necessary.

Here's a quick take. I'm sure it can be cleaned up further. I've also taken the liberty of fixing the delete before post id bug.

    express = require 'express'
    bodyParser = require 'body-parser'
    
    server = express()
    server.use bodyParser()
    
    books = [
      { id: 1, title: "Microsoft Visual C# 2012", author: "John Sharp" }
      { id: 2, title: "C# 5.0 in a nutshell", author: "Joseph Albahari" }
      { id: 3, title: "C# in Depth, 3rd Edition", author: "Jon Skeet" }
      { id: 4, title: "Pro ASP.NET MVC 5", author: "Adam Freeman" }
    ]
    
    findBook = (req, res, cb) ->
      book = books.filter (b) -> b.id is +req.params.id
      if book.length
        cb book[0]
      else
        res.statusCode = 404
        res.send "No book with ID = #{req.params.id}"
    
    server.get "/api/books", (req, res) ->
      res.send books
    
    server.get "/api/books/:id", (req, res) ->
      findBook req, res, (book) ->
        res.send book
    
    server.post "/api/books", (req, res) ->
      book = req.body
      book.id = 1 + Math.max.apply Math, books.map (b) -> b.id
      books = books.concat [book]
      res.send 200
    
    server.put "/api/books/:id", (req, res) ->
      findBook req, res, (book) ->
        updates = req.body
        ['title', 'author'].forEach (f) -> book[f] = updates[f]
        res.send 200

    server.delete "/api/books/:id", (req, res) ->
      findBook req, res, (book) ->
        books = books.filter (b) -> b.id isnt book.id
        res.send 200
    
    server.listen 3000
    console.log "server listening on localhost:3000"