-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
109 lines (95 loc) · 2.47 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
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
import express from "express";
import mongoose from "mongoose";
import Task from "./models/Task.js";
import * as dotenv from "dotenv";
import cors from "cors";
dotenv.config();
mongoose
.connect(process.env.DATABASE_URL)
.then(() => console.log("Connected to DB"));
const app = express();
const corsOptions = {
origin: ["http://127.0.0.1:5500", "https://my-todo.com"],
};
app.use(cors(corsOptions));
app.use(express.json());
function asyncHandler(handler) {
return async function (req, res) {
try {
await handler(req, res);
} catch (e) {
if (e.name === "ValidationError") {
res.status(400).send({ message: e.message });
} else if (e.name === "CastError") {
res.status(404).send({ message: "Cannot find given id." });
} else {
res.status(500).send({ message: e.message });
}
}
};
}
app.get(
"/tasks",
asyncHandler(async (req, res) => {
/**
* 쿼리 파라미터
* - sort: 'oldest'인 경우 오래된 태스크 기준, 나머지 경우 새로운 태스크 기준
* - count: 태스크 개수
*/
const sort = req.query.sort;
const count = Number(req.query.count) || 0;
const sortOption = {
createdAt: sort === "oldest" ? "asc" : "desc",
};
const tasks = await Task.find().sort(sortOption).limit(count);
res.send(tasks);
})
);
app.get(
"/tasks/:id",
asyncHandler(async (req, res) => {
const id = req.params.id;
const task = await Task.findById(id);
if (task) {
res.send(task);
} else {
res.status(404).send({ message: "Cannot find given id." });
}
})
);
app.post(
"/tasks",
asyncHandler(async (req, res) => {
const newTask = await Task.create(req.body);
res.status(201).send(newTask);
})
);
app.patch(
"/tasks/:id",
asyncHandler(async (req, res) => {
const id = req.params.id;
const task = await Task.findById(id);
if (task) {
Object.keys(req.body).forEach((key) => {
task[key] = req.body[key];
});
await task.save();
res.send(task);
} else {
res.status(404).send({ message: "Cannot find given id." });
}
})
);
app.delete(
"/tasks/:id",
asyncHandler(async (req, res) => {
const id = req.params.id;
const task = await Task.findByIdAndDelete(id);
if (task) {
res.sendStatus(204);
} else {
res.status(404).send({ message: "Cannot find given id." });
}
})
);
app.listen(process.env.PORT || 3000, () => console.log("Server Started"));