-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
107 lines (98 loc) · 2.6 KB
/
db.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
101
102
103
104
105
106
107
const spicedPg = require("spiced-pg");
const db = spicedPg(
process.env.DATABASE_URL ||
"postgres:postgres:postgres@localhost:5432/imageboard"
);
exports.getImages = function() {
return db
.query(
`SELECT * FROM images
ORDER BY id DESC
LIMIT 6`
)
.then(({ rows }) => rows);
};
exports.getFirstImageId = function () {
return db
.query(
`SELECT id FROM images
ORDER BY id ASC
LIMIT 1`
).then(({ rows }) => rows);
};
exports.getMoreImages = function(lowestId) {
return db
.query(
`SELECT id, url, username, title, description, created_at, (
SELECT id FROM images
ORDER BY id ASC
LIMIT 1
) AS "lowestId" FROM images
WHERE id < $1
ORDER BY id DESC
LIMIT 6`,
[lowestId]
)
.then(({ rows }) => rows).catch(err => {
console.log('err in getMoreImages in db.js: ', err);
});
};
exports.addImage = function(url, username, title, description) {
return db
.query(
`INSERT INTO images (url, username, title, description)
VALUES ($1, $2, $3, $4)
RETURNING *`,
[url, username, title, description]
)
.then(({ rows }) => rows);
};
// exports.getImage = function(id) {
// return db
// .query(
// `SELECT * FROM images
// WHERE id= $1`,
// [id]
// )
// .then(({ rows }) => rows);
// };
exports.getImage = function(id) {
return db
.query(
`SELECT *, (
SELECT id FROM images
WHERE id > $1
ORDER BY id ASC
LIMIT 1
) AS "previousId", (
SELECT id FROM images
WHERE id < $1
ORDER BY id DESC
LIMIT 1
) AS "nextId"
FROM images
WHERE id= $1`,
[id]
)
.then(({ rows }) => rows);
};
exports.getComments = function(img_id) {
return db
.query(
`SELECT * FROM comments
WHERE img_id=$1
ORDER BY id DESC`,
[img_id]
)
.then(({ rows }) => rows);
};
exports.addComment = function(comment, username, img_id) {
return db
.query(
`INSERT INTO comments (comment, username, img_id)
VALUES ($1, $2, $3)
RETURNING *`,
[comment, username, img_id]
)
.then(({ rows }) => rows);
};