-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbackend.js
More file actions
76 lines (65 loc) · 2.08 KB
/
Copy pathbackend.js
File metadata and controls
76 lines (65 loc) · 2.08 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
const debug = require('debug')('backend'),
{ Pool } = require('pg');
module.exports = function createTodoBackend(connectionString) {
const pool = new Pool({
connectionString: connectionString,
});
function query(query, params, callback) {
debug(`Query ${query} with params ${params}`);
pool.query(query, params, function(err, result) {
if (err) {
debug(`Database error ${err}`);
callback(err);
return;
}
callback(null, result.rows);
});
}
return {
all: function(callback) {
query('SELECT * FROM todos', [], callback);
},
get: function(id, callback) {
query('SELECT * FROM todos WHERE id = $1', [id], function(err, rows) {
callback(err, rows && rows[0]);
});
},
create: function(title, order, callback) {
query('INSERT INTO todos ("title", "order", "completed") VALUES ($1, $2, false) RETURNING *', [title, order], function(err, rows) {
callback(err, rows && rows[0]);
});
},
update: function(id, properties, callback) {
var assigns = [], values = [];
if ('title' in properties) {
assigns.push('"title"=$' + (assigns.length + 1));
values.push(properties.title);
}
if ('order' in properties) {
assigns.push('"order"=$' + (assigns.length + 1));
values.push(properties.order);
}
if ('completed' in properties) {
assigns.push('"completed"=$' + (assigns.length + 1));
values.push(properties.completed);
}
var updateQuery = [
'UPDATE todos',
'SET ' + assigns.join(', '),
'WHERE id = $' + (assigns.length + 1),
'RETURNING *'
];
query(updateQuery.join(' '), values.concat([id]), function(err, rows) {
callback(err, rows && rows[0]);
});
},
delete: function(id, callback) {
query('DELETE FROM todos WHERE id = $1 RETURNING *', [id], function(err, rows) {
callback(err, rows && rows[0]);
});
},
clear: function(callback) {
query('DELETE FROM todos RETURNING *', [], callback);
}
};
};