-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.js
85 lines (78 loc) · 2.24 KB
/
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const promise = require('bluebird');
const initOptions = {
promiseLib: promise
};
const pgp = require('pg-promise')(initOptions);
const config = {
// In production environment, host name is postgres container name from docker run or yml file
// In developer environment, host name needs to defined in env variables or launch.json
host: process.env.POSTGRES_HOST || 'postgres-db',
port: 5432,
database: 'example_database',
user: 'postgres',
password: 'example'
};
//const pgUri = 'postgres://postgres:example@postgres-db:5432/example_database';
const db = pgp(config);
console.log('connect to pgp');
//db.any('SELECT * FROM "user" WHERE "name" LIKE $1', ['%am%'])
//db.any('SELECT * FROM "user" LIMIT 50', ['%am%'])
// .then((data) => {
// console.log(data);
// })
// .catch((error) => {
// console.log(error);
// })
// //.finally(db.$pool.end);
function getAllUsers(cb) {
db.any('SELECT * FROM "users" LIMIT 500', [])
.then((data) => {
cb(null, data);
})
.catch((error) => {
cb(error, null);
})
//.finally(db.$pool.end);
}
function getUser(sourceId, cb) {
db.one('SELECT * FROM "users" WHERE "sourceId" = $1', [sourceId])
.then((data) => {
cb(null, data);
})
.catch((error) => {
cb(error, null);
})
//.finally(db.$pool.end);
}
function setUser(sourceId, hasNotification, notificationTime) {
getUser(sourceId, (error, data) => {
let queryString;
if (error != null) {
if (error.code === pgp.errors.queryResultErrorCode.noData) {
console.log('user not exists, use insert query');
queryString = 'INSERT INTO "users" ("sourceId", "hasNotification", "notificationTime") VALUES ($1, $2, $3)';
} else {
console.log(error);
}
} else {
console.log('user exists, use update query');
queryString = 'UPDATE "users" SET "hasNotification" = $2, "notificationTime" = $3 WHERE "sourceId" LIKE $1';
}
db.query(queryString, [sourceId, hasNotification, notificationTime])
.catch((error) => {
console.log('setUser:', error);
})
});
}
module.exports = {
getAllUsers,
getUser,
setUser,
errorCode: pgp.errors.queryResultErrorCode,
poolEnd: () => {
db.$pool.end;
},
end: () => {
pgp.end();
}
};