-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
112 lines (97 loc) · 2.54 KB
/
Copy pathapp.js
File metadata and controls
112 lines (97 loc) · 2.54 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const express = require("express");
const multer = require("multer");
const mongoose = require("mongoose");
const path = require("path");
const fs = require("fs");
const app = express();
const PORT = process.env.PORT || 9000;
if (!fs.existsSync("uploads")) {
fs.mkdirSync("uploads");
}
mongoose.connect(process.env.MONGO_URL);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Connected to MongoDB");
});
const postSchema = new mongoose.Schema({
title: String,
body: String,
images: [String],
videos: [String],
audio: [String],
});
const Post = mongoose.model("Post", postSchema);
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/");
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
},
});
const upload = multer({
storage: storage,
limits: { fileSize: 5000 * 1024 * 1024 }, // 5000MB in bytes
});
app.use("/uploads", express.static("uploads"));
const multiUpload = upload.fields([
{ name: "images" },
{ name: "videos" },
{ name: "audio" },
]);
app.post("/post", multiUpload, async (req, res) => {
try {
const { title, body } = req.body;
const images = req.files["images"]
? req.files["images"].map((file) => file.path)
: [];
const videos = req.files["videos"]
? req.files["videos"].map((file) => file.path)
: [];
const audio = req.files["audio"]
? req.files["audio"].map((file) => file.path)
: [];
const newPost = new Post({
title,
body,
images,
videos,
audio,
});
await newPost.save();
res.status(201).send("Post created successfully");
} catch (error) {
console.error("Post creation error:", error);
res.status(500).send(error.message);
}
});
app.get("/posts", async (req, res) => {
try {
const posts = await Post.find();
res.status(200).json(posts);
} catch (error) {
res.status(500).send(error.message);
}
});
app.get("/post/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) {
return res.status(404).send("Post not found");
}
res.status(200).json(post);
} catch (error) {
res.status(500).send(error.message);
}
});
app.get("/", async (req, res) => {
try {
res.status(200).send("Hello from world!");
} catch (error) {
res.status(500).send(error.message);
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});