あいつの日誌β

あいつの日誌です。

demo api server

This is my memo.

var express = require("express");
var app = express();

app.use(express.logger());
app.use(express.bodyParser());
app.use(app.router);
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

app.all('*', 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();
});

var ids = {}, resources ={};

function getId(target) {
    if ( ids[target] ) {
        return ++ids[target];
    }
    else {
        return ids[target] = 1;
    }
}

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

// list
app.get('/:resource', function (req, res) {
    var rows = getResource(req.params.resource);
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify({success:true, root:rows}));
    res.end();
});

// create
app.post('/:resource', function (req, res) {
    var row = req.body;
    row.id = getId(req.params.resource);
    
    var rows = getResource(req.params.resource);
    rows.push(row);

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify({success:true}));
    res.end();
});

// show
app.get('/:resource/:id', function (req, res) {
    var rows = getResource(req.params.resource);
  
    var row;
    for (var i = 0; i < rows.length; i ++) {
        if (rows[i].id == req.params.id ) {
           row = rows[i];
           break;
        } 
    }

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify({success:true, root:row}));
    res.end();
});

// update
app.put('/:resource/:id', function (req, res) {
    var rows = getResource(req.params.resource);
  
    var row;
    for (var i = 0; i < rows.length; i ++) {
        if (rows[i].id == req.params.id ) {
           rows[i] = req.body;
           rows[i].id = req.params.id;
           break;
        } 
    }

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify({success:true, root:row}));
    res.end();
});

// delete
app.delete('/:resource/:id', function (req, res) {
    var rows = getResource(req.params.resource);
  
    var row;
    for (var i = 0; i < rows.length; i ++) {
        if (rows[i].id == req.params.id ) {
           rows.splice(i, 1);
           break;
        } 
    }

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify({success:true}));
    res.end();
});


var port = 4000;
app.listen(port);
console.log('express running at http://localhost:%d', port);