forked from 0916dhkim/vscode-devcontainer-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.js
82 lines (74 loc) · 1.98 KB
/
app.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
/**
* Simple TODO REST server.
*/
const express = require("express");
const pgp = require("pg-promise")();
const app = express();
const PORT = process.env.PORT || 3000;
const connection = {
host: "db",
database: process.env.POSTGRES_DB,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD
};
const db = pgp(connection);
// Middlewares.
app.use(express.urlencoded({ extended: false }));
app.get("/", (req, res) => {
res.send("Hello, World!");
});
// CREATE
app.post("/todo", async (req, res) => {
const { task } = req.body;
db.one("INSERT INTO todo(task, finished) VALUES($1, $2) RETURNING id", [task, false])
.then(data => res.send(data))
.catch(e => {
res.status(500);
res.send({
error: `Database error: ${e}`
});
});
});
// READ
app.get("/todo", async (req, res, next) => {
db.any("SELECT * FROM todo")
.then(data => res.send(data))
.catch(e => {
res.status(500);
res.send({
error: `Database error: ${e}`
});
});
});
// UPDATE
app.post("/todo/finished", async (req, res) => {
const { id, finished } = req.body;
db.none("UPDATE todo SET finished = $1 WHERE id = $2", [finished, id])
.then(() => res.send({ status: "OK" }))
.catch(e => {
res.status(500);
res.send({
error: `Database error: ${e}`
});
});
});
// DELETE
app.delete("/todo", async (req, res) => {
const { id } = req.body;
db.none("DELETE FROM todo WHERE id = $1", [id])
.then(() => res.send({ status: "OK" }))
.catch(e => {
res.status(500);
res.send({
error: `Database error: ${e}`
});
});
});
// Error handlers.
app.use((req, res, next) => {
res.status(404);
res.send("Not Found");
});
app.listen(PORT, () => {
console.log(`App is listening on port ${PORT}.`);
});