あいつの日誌β

働きながら旅しています。

Build a RESTful API Using Node.js 2014

Build a RESTful API Using Node.js 2014

this tutorial is copied from here.

install

install node.js

% ndenv install v0.10.31 
% ndenv global v0.10.31
% ndenv rehash

install global commands

% npm install -g express-generator
% npm install -g coffee-script
% npm install -g coffeelint 
% npm install -g nodemon
% npm install -g mocha
% ndenv rehash
% express --version
4.9.0
% coffee --version
CoffeeScript version 1.8.0

install modules

% mkdir projectname && cd $_
% npm init
% npm install --save async
% npm install --save body-parser
% npm install --save coffee-errors
% npm install --save coffee-script
% npm install --save express
% npm install --save mongoose
% npm install --save supertest

Setting Up Our Server

create server.coffee like this

% cat server.coffee
require 'coffee-script'
require 'coffee-errors'

express    = require 'express'
bodyParser = require 'body-parser'

module.exports = app = express()

app.use bodyParser.urlencoded {extended:true}
app.use bodyParser.json()

port = process.env.PORT or 8080

router = express.Router()

router.get '/', (req, res)->
  res.json { message: 'hooray! welcome to our api!' }

app.use '/api', router

if not module.parent
  app.listen port
  console.log 'Magic happens on port ' + port

check it out

% nodemon server.coffee

prepare test case

create test/app_test.coffee like this

% cat test/app_test.coffee
process.env.NODE_ENV = 'test'

request = require 'supertest'
app = require '../server'

describe '/api', ->

  describe 'GET', ()->
    
    it 'should return 200 with json', (done)->
  
      request(app)
        .get('/api')
        .expect('Content-Type', /json/)
        .expect(200)
        .end (err, res)->
          do done

run it

% mocha --compilers coffee:coffee-script/register test/app_test.coffee
...
1 passing

Creating Our Database and Connecting

add test utils like this.

% cat test/utils.coffee
process.env.NODE_ENV = 'test'
mongoose = require 'mongoose'
async = require 'async'

module.exports =
  clear: (done)->
    
    collections = []
    for col of mongoose.connection.collections
      collections.push mongoose.connection.collections[col]

    async.eachSeries collections, (col, next)->
      col.remove -> do next
    , (e)->
      console.error e if e
      done()

  disconnect: (done)->
    mongoose.disconnect -> do done

modify test case like this

% cat test/app_test.coffee
testUtils = require './utils'
request = require 'supertest'
app = require '../server'

describe '/api/bears', ->

  before (done)->
    testUtils.clear(done)

  after (done)->
    testUtils.disconnect(done)
    
  describe 'GET', ->
    
    it 'should return 200 with bears', (done)->
  
      request(app)
        .get('/api/bears')
        .expect('Content-Type', /json/)
        .expect(200)
        .end (err, res)->
          # but still empty
          res.body.length is 0
          do done
          
  describe 'POST', ->
  
    it 'should create bear', (done)->
  
      request(app)
        .post('/api/bears')
        .send({name: 'bear'})
        .expect('Content-Type', /json/)
        .expect(200)
        .end (err, res)->
          # it's new bear
          res.body.length is 1
          do done
 
    it 'should return 200 with new bear', (done)->
  
      request(app)
        .get('/api/bears')
        .expect('Content-Type', /json/)
        .expect(200)
        .end (err, res)->
          do done

add bear model

% cat app/models/bear.coffee
mongoose = require 'mongoose'
Schema = mongoose.Schema
BearSchema = new Schema {name: String}
module.exports = mongoose.model 'Bear', BearSchema

modify server.coffee

% cat server.coffee
require 'coffee-script'
require 'coffee-errors'

express    = require 'express'
bodyParser = require 'body-parser'
mongoose   = require 'mongoose'

module.exports = app = express()

Bear = require './app/models/bear'

app.use bodyParser.urlencoded {extended:true}
app.use bodyParser.json()

if app.get('env') is 'test'
  mongoose.connect 'mongodb://localhost/myapp_test'
else
  mongoose.connect 'mongodb://localhost/myapp'

port = process.env.PORT or 8080

router = express.Router()

router.route('/bears')
  
  .post (req, res)->
    bear = new Bear()
    bear.name = req.body.name
    bear.save (e)->
      return res.send(e) if e
      res.json {message: 'Bear created!'}

  .get (req, res)->
    Bear.find (e, bears)->
      return res.send e if e
      res.json bears

app.use '/api', router

if not module.parent
  app.listen port
  console.log 'Magic happens on port ' + port

run test

% mocha --compilers coffee:coffee-script/register test/app_test.coffee
...
3 passing

enjoy:)