forked from kriasoft/react-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
81 lines (73 loc) · 1.88 KB
/
db.js
File metadata and controls
81 lines (73 loc) · 1.88 KB
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
77
78
79
80
81
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import db from 'pg';
import Promise from 'bluebird';
import { databaseUrl } from '../config';
// TODO: Customize database connection settings
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
db.defaults.ssl = true;
db.defaults.poolSize = 2;
db.defaults.application_name = 'RSK';
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
/**
* Promise-based wrapper for pg.Client
* https://github.com/brianc/node-postgres/wiki/Client
*/
function AsyncClient(client) {
this.client = client;
this.query = this.query.bind(this);
this.end = this.end.bind(this);
}
AsyncClient.prototype.query = function query(sql, ...args) {
return new Promise((resolve, reject) => {
if (args.length) {
this.client.query(sql, args, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
} else {
this.client.query(sql, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
}
});
};
AsyncClient.prototype.end = function end() {
this.client.end();
};
/**
* Promise-based wrapper for pg.connect()
* https://github.com/brianc/node-postgres/wiki/pg
*/
db.connect = (connect => callback => new Promise((resolve, reject) => {
connect.call(db, databaseUrl, (err, client, done) => {
if (err) {
if (client) {
done(client);
}
reject(err);
} else {
callback(new AsyncClient(client)).then(() => {
done();
resolve();
}).catch(error => {
done(client);
reject(error);
});
}
});
}))(db.connect);
export default db;