あいつの日誌β

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

Simple REST Demo Server 2014

This is my memo.

tree

% tree -I 'node_modules'
.
├── package.json
└── server.js

0 directories, 2 files

package.json

% cat package.json
{
  "name": "Gang2",
  "version": "0.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "restify": "~2.7.0",
    "save": "~0.0.20"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

server.js

% cat server.json
var restify = require('restify'),
    save = require('save');

var resources = {};

function getResource(name) {
    if (!resources[name]) {
        resources[name] = save(name);
    }
    return resources[name]
}

var server = restify.createServer({
    name: 'REST demo server'
})

server
    .use(restify.fullResponse())
    .use(restify.bodyParser())
    .use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Credentials", true);
        res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header("Access-Control-Allow-Headers", "Content-Type");
        next();
    });

server.post('/:resource', function(req, res, next) {

    if (req.params.name === undefined) {
        return next(new restify.InvalidArgumentError('Name must be supplied'))
    }

    getResource(req.params.resource).create({
        name: req.params.name
    }, function(error, resource) {
        if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)))
        res.send(201, resource)
    })
})

server.get('/:resource', function(req, res, next) {

    getResource(req.params.resource).find({}, function(error, resources) {
        res.send(resources)
    })
});

server.get('/:resources/:id', function(req, res, next) {

    getResource(req.params.resources).findOne({
        _id: req.params.id
    }, function(error, resource) {
        if (error) {
            return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)))
        }

        if (resource) {
            res.send(resource)
        } else {
            res.send(404)
        }
    })
})

server.put('/:resources/:id', function(req, res, next) {

    if (req.params.name === undefined) {
        return next(new restify.InvalidArgumentError('Name must be supplied'))
    }

    getResource(req.params.resources).update({
        _id: req.params.id,
        name: req.params.name
    }, function(error, resource) {
        
        if (error) {
            return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)));
        }

        res.send(resource)
    })
})

server.del('/:resources/:id', function(req, res, next) {

    getResource(req.params.resources).delete(req.params.id, function(error, user) {

        if (error) {
            return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)));
        }

        res.send()
    })
})

server.listen(3000, function() {
    console.log('%s listening at %s', server.name, server.url)
});

npm install

% npm install

run it

% node server.js

cURL

GET

% curl -i http://localhost:3000/users

POST

% curl -i -X POST -d 'name=taro' http://localhost:3000/users
% curl -i http://localhost:3000/users
% curl -i -X POST -d 'name=jiro' http://localhost:3000/users
% curl -i http://localhost:3000/users

PUT

% curl -i -X PUT -d 'name=ichiro' http://localhost:3000/users/1
% curl -i http://localhost:3000/users

DELETE

% curl -i -X DELETE http://localhost:3000/users/1
% curl -i http://localhost:3000/users