forked from sokube/simple-todo-list
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpgdb.js
94 lines (85 loc) · 2.93 KB
/
pgdb.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
86
87
88
89
90
91
92
93
94
const { Client } = require ('pg');
const client = new Client( {
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
password: process.env.DB_PASSWORD
});
// Connect and initialize the database with the todos table if not done already
client.connect()
client.on('connect', function () {
console.log("Connected to PostgreSQL server "+client.host+":" + client.port)
client.query('CREATE TABLE IF NOT EXISTS TODOS ( \
id serial NOT NULL, \
description varchar(256), \
complete boolean, \
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \
PRIMARY KEY(ID));');
});
var db = {
list_all_tasks: function () {
const query = 'SELECT id, description, complete FROM TODOS ORDER BY created ASC;'
client
.query(query)
.then(res => { return res.rows;} )
.catch(e => console.error(e.stack));
},
create_task:function (desc) {
const query = 'INSERT INTO TODOS(description,complete) VALUES ($1,$2) RETURNING id,description,complete;'
const values = [ desc, false ];
client
.query(query,values)
.then( r => { return;} )
.catch(e => res.send(err));
},
delete_task:function (taskid) {
const query = 'DELETE FROM TODOS where id=$1;'
const values = [ taskid ];
client
.query(query,values)
.then( r => { return;} )
.catch(e => res.send(err));
},
toggle_task:function (taskid) {
const query = 'UPDATE TODOS SET complete = NOT complete where id=$1 RETURNING *;'
const values = [ taskid ];
client
.query(query,values)
.then( r => { return;} )
.catch(e => res.send(err));
}
};
module.exports = db;
// // REST endpoints
// list_all_tasks = function () {
// const query = 'SELECT id, description, complete FROM TODOS ORDER BY created ASC;'
// client
// .query(query)
// .then(res => { return res.rows;} )
// .catch(e => console.error(e.stack));
// }
// create_task = function (desc) {
// const query = 'INSERT INTO TODOS(description,complete) VALUES ($1,$2) RETURNING id,description,complete;'
// const values = [ desc, false ];
// client
// .query(query,values)
// .then( r => { return;} )
// .catch(e => res.send(err));
// }
// delete_task = function (taskid) {
// const query = 'DELETE FROM TODOS where id=$1;'
// const values = [ taskid ];
// client
// .query(query,values)
// .then( r => { return;} )
// .catch(e => res.send(err));
// }
// toggle_task = function (taskid) {
// const query = 'UPDATE TODOS SET complete = NOT complete where id=$1 RETURNING *;'
// const values = [ taskid ];
// client
// .query(query,values)
// .then( r => { return;} )
// .catch(e => res.send(err));
// }