-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
65 lines (55 loc) · 1.72 KB
/
app.js
File metadata and controls
65 lines (55 loc) · 1.72 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
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import Task from './task.js';
import { DATABASE_URL } from './constants.js';
const app = express();
app.use(cors());
app.use(express.json());
await mongoose.connect(DATABASE_URL);
app.get('/tasks', async (req, res) => {
/** 쿼리 목록
* - count: 아이템 개수
* - sort: 정렬
*/
const count = Number(req.query.count) || 0;
const sortOption =
req.query.sort === 'oldest' ? ['createdAt', 'asc'] : ['createdAt', 'desc'];
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: '해당 id를 찾을 수 없습니다.' });
}
});
app.post('/tasks', async (req, res) => {
const newTask = await Task.create(req.body);
res.send(newTask);
});
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'));
console.log('DATABASE_URL:', DATABASE_URL);