This repository has been archived by the owner on Mar 21, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
76 lines (62 loc) · 2.17 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// ----------------------------------------------------------------------------
//
// 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')(require('pg'));
// ----------------------------------------------------------------------------
module.exports = function(opts) {
"use strict"
if (typeof opts === 'string') {
opts = {pg: opts};
}
// For legacy support when 'pg' was named 'conStr'.
else if (typeof opts.conStr !== 'undefined' &&
typeof opts.pg === 'undefined')
{
//opts.pg = opts.conStr;
}
// 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 || {};
//From http://ivc.com/blog/better-sql-strings-in-io-js-nodejs-part-2/
this.pg.sqltpl = function (pieces) {
var result = '';
var vals = [];
var substitutions = [].slice.call(arguments, 1);
for (var i = 0; i < substitutions.length; ++i) {
result += pieces[i] + '$' + (i + 1);
vals.push(substitutions[i]);
}
result += pieces[substitutions.length];
return {text: result, values: vals};
};
var connectionResults = yield pg.connectPromise(opts.pg);
this.pg[opts.name] = {
client: connectionResults[0],
done: connectionResults[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];
};
}
// ----------------------------------------------------------------------------