-
Notifications
You must be signed in to change notification settings - Fork 32
/
queries.js
100 lines (91 loc) · 2.31 KB
/
queries.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
95
96
97
98
99
100
var promise = require('bluebird');
var options = {
// Initialization Options
promiseLib: promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://localhost:5432/puppies';
var db = pgp(connectionString);
function getAllPuppies(req, res, next) {
db.any('select * from pups')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL puppies'
});
})
.catch(function (err) {
return next(err);
});
}
function getSinglePuppy(req, res, next) {
var pupID = parseInt(req.params.id);
db.one('select * from pups where id = $1', pupID)
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ONE puppy'
});
})
.catch(function (err) {
return next(err);
});
}
function createPuppy(req, res, next) {
req.body.age = parseInt(req.body.age);
db.none('insert into pups(name, breed, age, sex)' +
'values(${name}, ${breed}, ${age}, ${sex})',
req.body)
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one puppy'
});
})
.catch(function (err) {
return next(err);
});
}
function updatePuppy(req, res, next) {
db.none('update pups set name=$1, breed=$2, age=$3, sex=$4 where id=$5',
[req.body.name, req.body.breed, parseInt(req.body.age),
req.body.sex, parseInt(req.params.id)])
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Updated puppy'
});
})
.catch(function (err) {
return next(err);
});
}
function removePuppy(req, res, next) {
var pupID = parseInt(req.params.id);
db.result('delete from pups where id = $1', pupID)
.then(function (result) {
/* jshint ignore:start */
res.status(200)
.json({
status: 'success',
message: `Removed ${result.rowCount} puppy`
});
/* jshint ignore:end */
})
.catch(function (err) {
return next(err);
});
}
module.exports = {
getAllPuppies: getAllPuppies,
getSinglePuppy: getSinglePuppy,
createPuppy: createPuppy,
updatePuppy: updatePuppy,
removePuppy: removePuppy
};