-
Notifications
You must be signed in to change notification settings - Fork 0
/
api
67 lines (58 loc) · 2.24 KB
/
api
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
const express = require('express');
const multer = require('multer');
const mongoose = require('mongoose');
const app = express();
// 使用 multer 來處理檔案上傳
const upload = multer({ dest: 'uploads/' });
// 設置 MongoDB 連接
mongoose.connect('mongodb://localhost:27017/obituary', { useNewUrlParser: true, useUnifiedTopology: true });
// 設置訃聞模型
const Obituary = mongoose.model('Obituary', new mongoose.Schema({
mainPhoto: String,
obituaryPaper: String,
timeline: [{ date: String, event: String }],
carouselPhotos: [String],
messages: [{ name: String, content: String, photo: String }]
}));
// 創建訃聞
app.post('/api/obituaries', upload.single('photo'), async (req, res) => {
try {
const { mainPhoto, obituaryPaper, timeline, carouselPhotos } = req.body;
const obituary = new Obituary({
mainPhoto,
obituaryPaper,
timeline: JSON.parse(timeline),
carouselPhotos: JSON.parse(carouselPhotos),
messages: []
});
await obituary.save();
res.status(201).send(obituary);
} catch (error) {
res.status(500).send({ message: '創建訃聞失敗', error });
}
});
// 獲取訃聞
app.get('/api/obituaries/:id', async (req, res) => {
try {
const obituary = await Obituary.findById(req.params.id);
if (!obituary) return res.status(404).send({ message: '未找到訃聞' });
res.status(200).send(obituary);
} catch (error) {
res.status(500).send({ message: '獲取訃聞失敗', error });
}
});
// 提交留言
app.post('/api/messages', upload.single('photo'), async (req, res) => {
try {
const { name, content } = req.body;
const photo = req.file ? req.file.path : '';
const obituary = await Obituary.findById(req.body.obituaryId);
if (!obituary) return res.status(404).send({ message: '未找到訃聞' });
obituary.messages.push({ name, content, photo });
await obituary.save();
res.status(201).send({ message: '留言已提交' });
} catch (error) {
res.status(500).send({ message: '提交留言失敗', error });
}
});
app.listen(3000, () => console.log('Server is running on port 3000'));