-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.js
More file actions
95 lines (82 loc) · 2.11 KB
/
Copy pathindex.js
File metadata and controls
95 lines (82 loc) · 2.11 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");
const path = require("path");
const PORT = process.env.PORT || 5000;
// process.env.NODE_ENV => production or undefined
// middleware
app.use(cors());
app.use(express.json()); // req.body
if (process.env.NODE_ENV === "production") {
// service static content
// npm run build
app.use(express.static(path.join(__dirname, "client/build")));
}
// ROUTES
// get all todos
app.get("/todos", async (req, res) => {
try {
const allTodos = await pool.query("SELECT * from todo");
res.status(200).json(allTodos.rows);
} catch (err) {
console.error(err.message);
}
});
// get a todo
app.get("/todos/:id", async (req, res) => {
try {
const { id } = req.params;
const todo = await pool.query("SELECT * FROM todo WHERE todo_id = $1", [
id,
]);
res.status(200).json(todo.rows[0]);
} catch (err) {
console.error(err.message);
}
});
// create a todo
app.post("/todos", async (req, res) => {
try {
const { description } = req.body;
const newTodo = await pool.query(
"INSERT INTO todo (description) VALUES($1) RETURNING *",
[description]
);
res.status(200).json(newTodo.rows[0]);
} catch (err) {
console.error(err.message);
}
});
// update a todo
app.put("/todos/:id", async (req, res) => {
try {
const { id } = req.params;
const { description } = req.body;
await pool.query(
"UPDATE todo SET description = $1 WHERE todo_id = $2",
[description, id]
);
res.status(200).json("todo was updated");
} catch (err) {
console.error(err.message);
}
});
// delete a todo
app.delete("/todos/:id", async (req, res) => {
try {
const { id } = req.params;
await pool.query("DELETE FROM todo WHERE todo_id = $1", [
id,
]);
res.status(200).json("todo was deleted");
} catch (err) {
console.error(err.message);
}
});
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client/build/index.html"));
});
app.listen(PORT, () => {
console.log(`Server is starting on port ${PORT}`);
});