-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (66 loc) · 1.83 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
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const PORT = 3000;
// Middleware
app.use(bodyParser.json());
app.use(express.static('public'));
// MongoDB接続
mongoose.connect('mongodb://localhost:27017/kakeibo', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const entrySchema = new mongoose.Schema({
date: { type: Date, default: Date.now },
type: { type: String, enum: ['income', 'expense'] },
category: String,
amount: Number,
description: String,
});
const Entry = mongoose.model('Entry', entrySchema);
// Routes
app.get('/entries', async (req, res) => {
try {
const entries = await Entry.find();
res.json(entries);
} catch (err) {
res.status(500).send(err);
}
});
app.post('/entries', async (req, res) => {
try {
const newEntry = new Entry(req.body);
await newEntry.save();
res.json(newEntry);
} catch (err) {
res.status(500).send(err);
}
});
app.put('/entries/:id', async (req, res) => {
try {
const updatedEntry = await Entry.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (updatedEntry) {
res.json(updatedEntry);
} else {
res.status(404).send('Entry not found');
}
} catch (err) {
res.status(500).send(err);
}
});
app.delete('/entries/:id', async (req, res) => {
try {
const deletedEntry = await Entry.findByIdAndRemove(req.params.id);
if (deletedEntry) {
res.json(deletedEntry);
} else {
res.status(404).send('Entry not found');
}
} catch (err) {
res.status(500).send(err);
}
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});