[英]Koa: What is the most sensible way to connect to a database without an existing wrapper?
I am very new to node & koa, so please excuse my stupidity. 我是Node&Koa的新手,请原谅我的愚蠢。
I am not sure if I mess something up. 我不确定我是否搞砸了。 But I would like to use Koa together with OrientDB.
但是我想将Koa与OrientDB一起使用。 I can connect to OrientDB using Oriento (the module for Node).
我可以使用Oriento(Node的模块)连接到OrientDB。 And I would like to use the power of generators of Koa.
我想使用Koa发电机的力量。
Since the data in my OrientDB database relates to objects I'm using in my app, I would like to implement models (of course). 由于OrientDB数据库中的数据与我在应用程序中使用的对象有关,因此我想实现模型(当然)。 So I guess the connecting to the database part would go in to that.
因此,我想连接到数据库部分会涉及到这一点。
Say I had a model named "Task" then I would like it to expose a couple of methods and getters/setter. 假设我有一个名为“ Task”的模型,那么我希望它公开一些方法和getters / setter方法。 So Task.find();
所以Task.find(); should get all Tasks from the OrientDB Database
应该从OrientDB数据库中获取所有任务
As far as I understand it, I would hook that somewhere in the middleware stack. 据我了解,我会将其钩在中间件堆栈中的某个位置。 And it would be nice if I could use generators so that my middleware waits until it gets the data back, using yield.
如果可以使用生成器,以便中间件使用yield来等待数据返回,那将是很好的选择。 Some error handling would be good as well...
一些错误处理也将很好。
With all that said: 话虽如此:
Thanks! 谢谢!
I've never used orient-db, but looking at the github page it looks like it offers a connection pool and returns promises. 我从未使用过orient-db,但在github页面上看,它似乎提供了连接池并返回了promise。 Based on that I would do something like this:
基于此,我将执行以下操作:
// in utils/oriento.js or similar
// instantiate it once and share in multiple places(models), since it offers
// connection pooling
var Oriento = require('oriento');
var server = Oriento({
host: 'localhost',
port: 2424,
username: 'root',
password: 'yourpassword'
});
var db = server.use({
name: 'mydb',
username: 'admin',
password: 'admin'
});
module.exports = db;
then for models: 然后对于模型:
// models/item.js
var db = require('../utils/oriento.js');
var Item = function(props){
};
Item.findById = function(id){
// db.query returns a promise
return db.query('select from OItem where id=:id', {
params: {
id: id
},
limit: 1
});
}
// add getters, setters, find etc...
module.exports = Item;
then in controllers: 然后在控制器中:
// server.js or wherever
var Item = require('./models/item');
app.get('/:id', function *(){
var id = this.params.id;
this.body = yield Item.findById(id);
}
Hopefully this helps 希望这会有所帮助
You might want to checkout my screencasts on koajs at http://knowthen.com 您可能想在http://knowthen.com上查看有关koajs的截屏视频
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.