如何连接CouchDb与HapiJs



我有一个使用HapiJs框架为Node编写的应用程序,并希望将其连接到CouchDb数据库,但我很难找到这样做的代码。

有谁能帮我写代码吗?"正常"的做法是什么?

干杯!

couchdb不需要任何框架。一切都可以通过rest api获得。只需使用请求模块向api发出请求。举几个例子:-

读取文档

 request.get("http://localhost:5984/name_of_db/id_of_docuement",
        function(err,res,data){
      if(err) console.log(err);  
     console.log(data);
 });

从视图中读取

    request.get(
    "http://localhost:5984/name_of_db/_design/d_name/_view/_view_name",
        function(err,res,data){
      if(err) console.log(err);  
     console.log(data);
 });

整个api都记录在这里

不需要管理连接或处理数据库的打开和关闭,而您可能正在处理其他数据库。只需启动couchdb并开始从应用程序发出请求。

但是,如果您发现直接向api发出请求对您来说有点麻烦,那么您可以尝试使用nano,它为使用couchdb提供了更好的语法。

一些代码片段

好吧,我不熟悉happy,所以我会告诉你如何使用request。

考虑文档

中的这个例子
var Hapi = require('hapi');
var server = new Hapi.Server(3000);
var request = require("request");
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
    reply('Hello, world!');
}
});
server.route({
method: 'GET',
path: '/{name}',
handler: function (req, rep) {
         request.get("http://localhost:5984/name_of_db/id_of_docuement",
        function(err,res,data){
      if(err) console.log(err);  
     rep(data);
 });
}
});
server.start(function () {
console.log('Server running at:', server.info.uri);
});

当您调用/端点时,它的请求处理程序被执行。它向couchdb端点发出请求以获取文档。除此之外,您不需要任何东西来连接到couchdb

另一个选择是hapi-couchdb插件(https://github.com/harrybarnard/hapi-couchdb)。

使用它比直接调用Couch API更"快乐"一点。

下面是插件文档中的一个示例:

var Hapi = require('hapi'),
    server = new Hapi.Server();
server.connection({
    host: '0.0.0.0',
    port: 8080
});
// Register plugin with some options
server.register({
    plugin: require('hapi-couchdb'),
    options: {
        url: 'http://username:password@localhost:5984',
        db: 'mycouchdb'
    }
}, function (err) {
    if(err) {
        console.log('Error registering hapi-couchdb', err);
    } else {
        console.log('hapi-couchdb registered');
    }
});
// Example of accessing CouchDb within a route handler
server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        var CouchDb = request.server.plugins['hapi-couchdb'];
        // Get a document from the db
        CouchDb.Db.get('rabbit', { revs_info: true }, function(err, body) {
            if (err) {
                throw new Error(CouchDb.Error(error); // Using error decoration convenience method
            } else {
                reply(body);
            });
    }
});
server.start(function() {
    console.log('Server running on host: ' + server.info.uri);
});

最新更新