-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
97 lines (79 loc) · 2.47 KB
/
server.js
File metadata and controls
97 lines (79 loc) · 2.47 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
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require('body-parser');
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const app = express();
const PORT = process.env.PORT || 8080;
// Middleware
app.use(bodyParser.json());
app.use(express.static("public"));
app.use("/uploads", express.static("uploads"));
// Connect to MongoDB
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/sendretrieve";
mongoose.connect(MONGODB_URI, {
});
// Set up file storage
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const uploadPath = path.join(__dirname, "uploads");
if (!fs.existsSync(uploadPath)) {
fs.mkdirSync(uploadPath);
}
cb(null, uploadPath);
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage });
// Define Schema
const dataSchema = new mongoose.Schema({
id: { type: String, unique: true },
text: String,
fileUrl: String,
createdAt: { type: Date, default: Date.now, expires: 86400 },
});
const Data = mongoose.model("Data", dataSchema);
// Generate a 4-digit unique ID
const generateId = async () => {
let id;
let exists;
do {
id = Math.floor(1000 + Math.random() * 9000).toString();
exists = await Data.findOne({ id });
} while (exists);
return id;
};
// Endpoint to send data (text or file)
app.post("/send", upload.single("file"), async (req, res) => {
const { text } = req.body;
const file = req.file;
if (!text && !file) {
return res.status(400).json({ error: "Text or file is required" });
}
const id = await generateId();
const fileUrl = file ? `/uploads/${file.filename}` : null;
const newData = new Data({ id, text, fileUrl });
await newData.save();
res.json({ id });
});
// Endpoint to retrieve data
app.get("/retrieve/:id", async (req, res) => {
const { id } = req.params;
const record = await Data.findOne({ id });
if (!record) {
return res.status(404).json({ error: "Data not found or expired" });
}
res.json({ text: record.text, fileUrl: record.fileUrl });
});
// Serve the index.html file
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});