-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
111 lines (91 loc) · 2.54 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
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
require("dotenv").config();
const cors = require("cors");
const express = require("express");
const connectDB = require("./connectDB");
const Notes = require("./models/Notes");
const app = express();
const PORT = process.env.PORT || 8000;
connectDB();
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Get All Notes
app.get("/api/notes", async (req, res) => {
try {
const data = await Notes.find({});
if (!data) {
throw new Error("An error occured while fetching notes.");
}
res.status(200).json(data);
} catch (error) {
res.status(500).json({ error: "An error occured while fetching notes..." });
}
});
// Get Note by ID
app.get("/api/notes/:id", async (req, res) => {
try {
const noteId = req.params.id;
const data = await Notes.findById(noteId);
if (!data) {
throw new Error("An error occured while fetching notes.");
}
res.status(200).json(data);
} catch (error) {
res.status(500).json({ error: "An error occured while fetching notes..." });
}
});
// Create A Note
app.post("/api/notes", async (req, res) => {
try {
const { title, description } = req.body;
const data = await Notes.create({ title, description });
if (!data) {
throw new Error("An error occured while creating a note.");
}
res.status(201).json(data);
} catch (error) {
res
.status(500)
.json({ error: "An error occured while creating a note..." });
}
});
// Update A Note
app.put("/api/notes/:id", async (req, res) => {
try {
const noteId = req.params.id;
const { title, description } = req.body;
const data = await Notes.findByIdAndUpdate(noteId, { title, description });
if (!data) {
throw new Error("An error occured while updating a note.");
}
res.status(201).json(data);
} catch (error) {
res
.status(500)
.json({ error: "An error occured while updating a note..." });
}
});
// Delete A Note by ID
app.delete("/api/notes/:id", async (req, res) => {
try {
const noteId = req.params.id;
const data = await Notes.findByIdAndDelete(noteId);
if (!data) {
throw new Error("An error occured while deleting a note.");
}
res.status(201).json(data);
} catch (error) {
res
.status(500)
.json({ error: "An error occured while deleting a note..." });
}
});
app.get("/", (req, res) => {
res.json("hello mate!");
});
app.get("*", (req, res) => {
res.sendStatus(404);
});
app.listen(PORT, () => {
console.log(`server is running on port ${PORT}`);
});