-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
123 lines (75 loc) · 2.07 KB
/
server.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
const express = require('express');
const app = express();
const cors= require('cors');
const path= require('path');
const pool= require('./db');
require('dotenv').config();
const port= process.env.PORT||5000;
//middleware
app.use(express.json());
app.use(cors());
// app.use(express.static(path.join(__dirname, 'client/build')));
//Environment
if (process.env.NODE_ENV==='production') {
app.use(express.static(path.join(__dirname, 'client/build')));
}
//get all todos
app.get("/todos", (req,res)=>{
const alltodos= "SELECT * FROM todo"
pool.query(alltodos, (err, response)=>{
if(err){console.log(err)};
res.json(response.rows);
});
})
//Get single todo
app.get("/todos/:id", async (req,res)=>{
try{
const {id}= await req.params;
const alltodos= await pool.query("SELECT * FROM todo WHERE todo_id=$1", [id]);
res.json(alltodos.rows)
;
}catch(err){
console.log(err)
}
})
//Update single todo
app.put("/todos/:id", async (req,res)=>{
try{
const {id}= await req.params;
const {description}= await req.body
const updateToDo= await pool.query("UPDATE todo SET description=$1 WHERE todo_id= $2 RETURNING *", [description, id]);
res.json(updateToDo.rows[0])
;
}catch(err){
console.log(err)
}
})
//delete
app.delete("/todos/:id", async (req,res)=>{
try{
const {id}= await req.params;
const {description}= await req.body
const deleteToDo= await pool.query("DELETE FROM todo WHERE todo_id= $1 RETURNING *", [ id]);
res.json("Todo was deleted")
;
}catch(err){
console.log(err)
}
})
//Create todo
app.post("/addtodo", async (req, res)=>{
try{
console.log(req.body)
const {description}=req.body;
const newTodo= await pool.query("INSERT INTO todo (description) VALUES($1) RETURNING *", [description]);
res.json(newTodo.rows[0])
}catch(err){
console.log(message.err);
}
})
app.get("*", (req, res)=>{
res.sendFile(path.join(__dirname, "client/build/index.html"))
})
app.listen(port, ()=>{
console.log(`port listening on port ${port}`)
})