-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
71 lines (60 loc) · 1.98 KB
/
app.js
File metadata and controls
71 lines (60 loc) · 1.98 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
import express from 'express';
import mongoose from 'mongoose';
import tasks from './seedData.js';
import { DATABASE_URL } from './constants.js';
import Task from './task.js';
import cors from 'cors';
const app = express();
app.use(cors());
app.use(express.json());
await mongoose.connect(DATABASE_URL);
app.post('/tasks', async (req, res) => {
const newTask = await Task.create(req.body);
res.status(201).send(newTask);
});
//라우트 : 서버에서 특별한 경로
app.get('/tasks', async (req, res) => {
/** 쿼리 파라미터
* - sort: 'oldest'인 경우 오래된 태스크 기준, 나머지 경우 새로운 태스크 기준
* - count: 태스크 개수
*/
//express sort라는 쿼리파라미터 보내면 자동으로 넣어준다.
const sort = req.query.sort;
const count = Number(req.query.count) || 0; //넘어온게 형변환이 안되서NaN이면 0을 넣어준다
const sortOption = sort === 'oldest' ? ['createdAt', 'asc'] : ['createdAt', 'desc'];
if (count === 0) {
return res.json([]);
}
const tasks = await Task.find().limit(count).sort([sortOption]);
res.send(tasks);
});
app.get('/tasks/:id', async (req, res) => {
const task = await Task.findById(req.params.id);
if (task) {
res.send(task);
} else {
res.status(404).send({ message: 'Cannot find given id.' });
}
});
app.patch('/tasks/:id', async (req, res) => {
const task = await Task.findById(req.params.id);
if (task) {
const { body } = req;
Object.keys(body).forEach((key) => {
task[key] = body[key];
});
await task.save();
res.send(task);
} else {
res.status(404).send({ message: '해당 id를 찾을 수 없습니다.' });
}
});
app.delete('/tasks/:id', async (req, res) => {
const task = await Task.findByIdAndDelete(req.params.id);
if (task) {
res.sendStatus(200);
} else {
res.status(404).send({ message: '해당 id를 찾을 수 없습니다.' });
}
});
app.listen(process.env.PORT || 3000, () => console.log('Server Started'));