-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb-postgres.js
66 lines (52 loc) · 1.31 KB
/
db-postgres.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
'use strict';
var Promise = require('promise');
var pg = require('pg');
var connectionString = process.env.DATABASE_URL;
pg.connect(connectionString, function (err, client, done) {
if (err) {
done();
return;
}
var query = client.query('CREATE TABLE IF NOT EXISTS members(id text PRIMARY KEY, created_at timestamp)');
query.on('end', function () {
done();
});
});
function putItem (id) {
return new Promise(function (resolve, reject) {
pg.connect(connectionString, function (err, client, done) {
if (err) {
done();
return reject();
}
var query = client.query('INSERT INTO members VALUES($1, now())', [ id ]);
query.on('end', function() {
done();
return resolve();
});
});
});
}
function getItem (id) {
return new Promise(function (resolve, reject) {
pg.connect(connectionString, function (err, client, done) {
if (err) {
done();
return reject();
}
var results = [];
var query = client.query('SELECT * FROM members WHERE id=($1)', [id]);
query.on('row', function (row) {
results.push(row);
});
query.on('end', function() {
done();
return resolve(results.length > 0);
})
});
});
}
module.exports = {
put: putItem,
get: getItem
};