-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (47 loc) · 1.37 KB
/
index.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
const express = require("express");
const cors = require('cors')
const app = express();
const path = require("path");
require('dotenv').config()
app.use(express.json());
app.use(cors())
app.use(express.static(path.join(__dirname, "../frontend")));
let todos = [];
app.get("/", (req, res) => {
res.status(202).json(todos);
});
app.post("/", (req, res) => {
let todo = {
id: todos.length + 1,
title: req.body.title,
date: req.body.date || null,
isComplete: req.body.isComplete || false,
};
todos.push(todo);
res.status(202).json(todo);
});
app.put("/:id", (req, res) => {
const id = parseInt(req.params.id);
const todo = todos.find((todo) => todo.id === id);
if (!todo) {
res.status(404).json({ error: "Todo not Found" });
}
todo.title = req.body.title || todo.title;
todo.date = req.body.date || todo.date;
todo.isComplete =
req.body.isComplete !== undefined ? req.body.isComplete : todo.isComplete;
res.json(todo);
});
app.delete("/:id", (req, res) => {
const id = parseInt(req.params.id);
const index = todos.findIndex((todo) => todo.id === id);
if (index === -1) {
res.status(404).json({ error: "Todo not Found" });
}
todos.splice(index, 1);
res.status(202).send({ msg: "Todo Deleted Sucessfully!!" });
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on ${port}`);
});