我有一个使用HapiJs框架编写的应用程序,并希望将其连接到CouchDb数据库,但我很难找到这样做的代码。
任何人都可以帮我解决这个问题吗?这种“正常”的做法是什么?
干杯!
答案 0 :(得分:3)
你不需要couchdb的任何框架。一切都可以通过休息api获得。只需使用request模块向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记录在案here
无需管理连接或处理您可能正在对其他数据库执行的数据库的打开和关闭。只需启动couchdb并开始从您的应用程序发出请求。
但是,如果您发现直接向api发出请求对您来说有点麻烦,那么您可以尝试使用nano来提供更好的语法来处理couchdb。
一些代码片段
好吧所以我不喜欢hapi所以我会告诉你如何处理请求。
从docs
中考虑这个例子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。
答案 1 :(得分:0)
另一个选项可能是hapi-couchdb插件(https://github.com/harrybarnard/hapi-couchdb)。
使用它比直接调用Couch API更像“hapi-like”。
以下是插件文档中的示例:
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);
});