forked from chilts/koa-pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (44 loc) · 1.43 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// ----------------------------------------------------------------------------
//
// http://npm.im/koa-pg
//
// Copyright (c) 2013 Andrew Chilton. All Rights Reserved.
//
// License : MIT - http://chilts.mit-license.org/2013/
//
// ----------------------------------------------------------------------------
// npm
var pg = require('co-pg')
// ----------------------------------------------------------------------------
module.exports = function(opts) {
"use strict"
if ( typeof opts === 'string' ) {
opts = { conStr : opts };
}
// set this db name
opts.name = opts.name || 'db';
return function *koaPg(next) {
// set up where we store all the DB connections
this.pg = this.pg || {};
var connect = yield pg.connect_(opts.conStr)
this.pg[opts.name] = {
client : connect[0],
done : connect[1],
}
// yield to all middlewares
try {
yield next
}
catch (e) {
// Since there was an error somewhere down the middleware,
// then we need to throw this client away.
this.pg[opts.name].done(e)
delete this.pg[opts.name];
throw e
}
// on the way back up the stack, release the client
this.pg[opts.name].done()
delete this.pg[opts.name]
}
}
// ----------------------------------------------------------------------------