I am trying to implement a db access layer within my koa application. This works fine:
var sqlite3 = require('co-sqlite3');
var services = require('./services/services');
app.use(function *(next){
this.db = yield sqlite3(services.file);
yield next
});
but I don't want to expose the database to every middleware in the app. In order to prevent this, I tried running .setup()
outside of the middleware: services.setup();
which is defined as:
var models = require('../models/models');
var path = require('path');
var sqlite3 = require('co-sqlite3');
module.exports = {
file: path.join(__dirname, '../data/db.db'),
setup: function () {
var database = yield sqlite3(this.file);
console.log('Database connected...');
database.run("PRAGMA foreign_keys = ON;");
database.run("DROP TABLE IF EXISTS BLOG_POST_BODIES; DROP TABLE IF EXISTS BLOG_POSTS;");
database.run(models.blog_posts);
database.run(models.users);
console.log('database created...');
database.run("INSERT INTO BLOG_POST_BODIES(BODY) VALUES('HELLO WORLD');");
var x = database.run("SELECT * FROM BLOG_POST_BODIES");
console.log(x);
}
};
the models
objects just has scripts to run to create the blog posts and user tables.
The line giving me trouble is var database = yield sqlite3(this.file);
It gives me the following error:
var database = yield sqlite3(this.file);
^^^^^^^
SyntaxError: Unexpected identifier
Which I guess is right because there's nothing to yield
forward to. But when I make setup()
a generator function it does not execute. Likewise, when I remove the yield
statement it tells me that database.run is not a function
.
I'm stuck on this, can't figure out how to implement it properly.
Edit:
If I make .setup()
a generator function and have all the database
calls yield
then it creates the tables and executes everything as expected...
app.use(function *(next){
this.db = yield services.setup();
yield next
});
But I don't want to expose the db to all the other middlewares, so I'm back to the same original problem.
How can I set up the co-sqlite3
database without including it in my middlewares?