Tech Tips

  1. Uncategorized
  2. 64 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”.

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…