-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
98 lines (78 loc) · 2.32 KB
/
server.js
File metadata and controls
98 lines (78 loc) · 2.32 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
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
import express from 'express';
import cors from 'cors';
import { apiReference } from '@scalar/express-api-reference';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const app = express();
app.use(cors());
app.use(express.json());
// Create API reference middleware
app.use(
'/api-reference',
apiReference({
url: '/openapi.json',
})
);
app.get('/openapi.json', (req, res) => {
res.sendFile(path.join(path.dirname(__filename), 'openapi.json'));
});
// In-memory storage for notes
let notes = [];
let nextId = 1;
// Get all notes
app.get('/notes', (req, res) => {
res.json(notes);
});
// Get a single note by ID
app.get('/notes/:id', (req, res) => {
const note = notes.find(n => n.id === parseInt(req.params.id));
if (!note) {
return res.status(404).json({ message: 'Note not found' });
}
res.json(note);
});
// Create a new note
app.post('/notes', (req, res) => {
const { title, content } = req.body;
if (!title || !content) {
return res.status(400).json({ message: 'Title and content are required' });
}
const newNote = {
id: nextId++,
title,
content,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
notes.push(newNote);
res.status(201).json(newNote);
});
// Update a note
app.put('/notes/:id', (req, res) => {
const noteIndex = notes.findIndex(n => n.id === parseInt(req.params.id));
if (noteIndex === -1) {
return res.status(404).json({ message: 'Note not found' });
}
const { title, content } = req.body;
if (!title || !content) {
return res.status(400).json({ message: 'Title and content are required' });
}
const updatedNote = { ...notes[noteIndex], title, content, updatedAt: new Date().toISOString() };
notes[noteIndex] = updatedNote;
res.json(updatedNote);
});
// Delete a note
app.delete('/notes/:id', (req, res) => {
const noteIndex = notes.findIndex(n => n.id === parseInt(req.params.id));
if (noteIndex === -1) {
return res.status(404).json({ message: 'Note not found' });
}
notes.splice(noteIndex, 1);
res.status(204).send();
});
const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
console.log(`API Reference available at http://localhost:${PORT}/api-reference`);
});