Tech Tips

  1. 未分類
  2. 14 view

[node.js][express][coffeescript] RESTful API part1


Make RESTful API with node.js, express and coffee script.

Prepare Environment

[Install node.js]
$ git clone git:// ~/.nvm
$ vim ~/.bashrc
source ~/.nvm/
$ 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

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 =


	describe 'validate',->
		before ->
			params =
				uid : 2354

			@requestline2 = new Requestline(params)

		it 'should return true', ->

Compile and connect with express

$mocha --compilers coffee:coffee-script spec/
$coffee -b -c models/ -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");

	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”.

未分類 recent post

  1. Install sbt 1.0.0 and run sample template

  2. Visualization of Neural Network and its Train…

  3. [Machine Learning]Created docker image includ…

  4. [Node.js]How to write batch script with Node.…

  5. Web Server Contribution by Vagrant and Ansibl…