0

如何使用node.js + perfectapi针对MongoDB创建服务器端 API ?

我因此设置了一个 Mongo 数据库:

dbpath = /Users/me/srv/db
bind_ip = 127.0.0.1
noauth = true
verbose = true

一个像这样的完美api脚本srv.js:

var mongo = require('mongodb'), Server = mongo.Server, Db = mongo.Db;
var db = new Db('timedb',new Server('localhost',27017,{auto_reconnect:true},{}));

db.open
(
    function(error,unused)
    {
        if(error) console.log("Cannot connect to database.");
        else console.log("We are now connected to the database.");
    }
);

var perfectapi = require('perfectapi');
var path = require('path');
var configPath = path.resolve(__dirname,'api.json');
var parser = new perfectapi.Parser();

parser.on
(
    "create",
    function(config,callback)
    {
        console.log(config)
        db.collection
        (
            'times',
            function(error,collection)
            {
                if(error) 
                {
                    console.log("Error in collection");
                    callback(error);
                }
                else
                {
                    console.log(config.options.time);
                    console.log("Success in collection");
                    collection.insert
                    (
                        config.options,
                        {safe:true},
                        function(error,callback)
                        {
                            if(error) console.log("Error inserting: "+error);
                            else
                            {
                                db.close();
                                callback(null,{"guid":"123"});
                            }
                        }
                    );
                }
            }
        );
    }
);

module.exports = parser.parse(configPath);

和这样的 api.json:

{
    "exports":"srv",
    "path":"api/v1",
    "signature":
    [
        {
            "name":"create",
            "synopsis":"Create a new record.",
            "verb":"POST",
            "options":
            [
                {"option":"time","required":true}
            ],
            "returns":
            [
                {"name":"guid","description":"The ID of the new record."}
            ]
        }
    ]
}

当我运行它时

node srv.js create --time 2012-09-10

我明白了

{ environment: {}, options: { time: '2012-09-10' } }
2012-09-10
Success in collection
We are now connected to the database.

然后脚本挂起并且没有在磁盘上创建数据库。另一方面,如果我停止 MongoDB 并再次运行脚本,我会得到

{ environment: {}, options: { time: '2012-09-10' } }
2012-09-10
Success in collection
Cannot connect to database.

脚本终止。

4

0 回答 0