How do I create a server-side API against a MongoDB using node.js + perfectapi?
I have setup a Mongo database thus:
dbpath = /Users/me/srv/db
bind_ip = 127.0.0.1
noauth = true
verbose = true
a perfectapi script srv.js like this:
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);
and a api.json like this:
{
"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."}
]
}
]
}
When I run it with
node srv.js create --time 2012-09-10
I get
{ environment: {}, options: { time: '2012-09-10' } }
2012-09-10
Success in collection
We are now connected to the database.
and then the script hangs and no database is created on disk. If on the other hand I stop MongoDB and run the script again, I get
{ environment: {}, options: { time: '2012-09-10' } }
2012-09-10
Success in collection
Cannot connect to database.
and the script terminates.