Koa: What is the most sensible way to connect to a database without an existing wrapper?

1.5k views Asked by At

I am very new to node & koa, so please excuse my stupidity.

I am not sure if I mess something up. But I would like to use Koa together with OrientDB. I can connect to OrientDB using Oriento (the module for Node). And I would like to use the power of generators of 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). 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. So Task.find(); should get all Tasks from the OrientDB Database

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. Some error handling would be good as well...

With all that said:

  • Are my assumptions correct? Or is there a better way?
  • Do I have to do that all myself? Or am I missing modules that facilitate what I am planning?
  • What would be a good point to start learning on how to properly do something like that?
  • Should I just look at existing wrappers for mongodb/mysql/whatever and abstract from that?

Thanks!

1

There are 1 answers

1
James Moore On

I've never used orient-db, but looking at the github page it looks like it offers a connection pool and returns promises. 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