Target
Make RESTful API with node.js, express and coffee script.Prepare Environment
[Install node.js] $ git clone git://github.com/creationix/nvm.git ~/.nvm $ vim ~/.bashrc source ~/.nvm/nvm.sh $ source ~/.bashrc $ nvm install v0.8.7 $ vim ~/.bashrc nvm use v0.8.7 $ source ~/.bashrc [Install express and coffeescript] $npm install express ejs coffee-script [Create Template] $express -e -t ejs restfulapi [Install mocha and chai for test] $npm install mocha chai
Write model with Coffee Script
Try to make simple validate model for get parameter.class Requestline constructor: (params) -> @params = params @validator = "uid" : /^[0-9]+$/ getParams: -> return @params validate: -> for key, value of @params if key of @validator and @validator[key].test(value) == false return false return true exports.Requestline = Requestline
chai = require 'chai' expect = chai.expect chai.should() Requestline = require('../models/requestline').Requestline describe 'Requestline',-> describe 'getParams',-> before -> params = key1 : 'val1' key2 : 'val2' @requestline1 = new Requestline(params) it 'should return {key1:val1,key2:val2}', -> expected = 'key1':'val1' 'key2':'val2' @requestline1.getParams()['key1'].should.equal(expected['key1']) @requestline1.getParams()['key2'].should.equal(expected['key2']) describe 'validate',-> before -> params = uid : 2354 @requestline2 = new Requestline(params) it 'should return true', -> @requestline2.validate().should.be.true
Compile and connect with express
[Test] $mocha --compilers coffee:coffee-script spec/requestline_spec.coffee [Compile] $coffee -b -c models/requestline.coffee -o libs/requestline.js
/* * GET home page. */ var requestline = require('../libs/requestline'); exports.index = function(req, res){ var reqline = new requestline['Requestline'](req.query); console.log("Query Parameters"); console.log(reqline.getParams()); if (reqline.validate()) { res.json([{ author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"}]); } else { res.json({ error : { type : "Qeury Syntax Error", message : "Query Syntax Error"}}); } //res.render('index', { title: 'Express'}); };
And then, type “node app.js”.