-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
150 lines (123 loc) Β· 5.37 KB
/
Copy pathserver.js
File metadata and controls
150 lines (123 loc) Β· 5.37 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const xlsx = require('xlsx');
const fs = require('fs');
const path = require('path');
const fileUpload = require('express-fileupload');
const cloudinary = require('cloudinary').v2;
const app = express();
const PORT = 10000;
const HOSTNAME = '0.0.0.0';
// π Middleware
app.use(cors({ origin: '*' })); // Allow all origins (for ngrok)
app.use(bodyParser.json());
app.use(fileUpload());
app.use(express.static('public'));
app.use('/output', express.static(path.join(__dirname, 'output')));
// π₯οΈ Cloudinary Configuration
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
});
mongoose.set('strictQuery', true);
// π MongoDB Connection
mongoose.connect(process.env.MONGO_URI, {})
.then(() => console.log('β
MongoDB connected successfully'))
.catch((err) => console.error('β MongoDB connection error:', err));
// π MongoDB Schema and Model
const familySchema = new mongoose.Schema({
head: Object,
spouse: Object,
sons: Array,
daughters: Array,
father: Object,
mother: Object,
fatherInLaw: Object,
motherInLaw: Object,
address: String,
cloudinaryExcelUrl: String, // π Added field for Excel URL
});
const Family = mongoose.model('Family', familySchema);
// π€ Image Upload Endpoint
app.post("/upload", async (req, res) => {
if (!req.files || !req.files.file) {
return res.status(400).json({ msg: "No file was uploaded" });
}
const file = req.files.file; // Uploaded file
const fileName = file.name.split(".")[0]; // Remove extension for public_id
try {
// Convert file buffer to base64
const uploadStr = `data:${file.mimetype};base64,${file.data.toString("base64")}`;
const result = await cloudinary.uploader.upload(uploadStr, {
folder: "uploads", // Cloudinary folder
resource_type: "auto",
public_id: fileName, // Set file name
overwrite: true, // If file exists, overwrite it
});
res.json({
message: "β
Image uploaded successfully!",
fileName: file.name,
cloudinaryUrl: result.secure_url,
});
} catch (error) {
console.error("β Cloudinary Upload Error:", error);
res.status(500).json({ message: "Failed to upload image", error });
}
});
// π₯ Submit Form Endpoint
app.post('/submit-form', async (req, res) => {
try {
const familyData = req.body;
// π Check if Family already exists
const existingFamily = await Family.findOne({ 'head.name': familyData.head.name });
if (existingFamily) {
return res.status(400).json({ message: `Family with head name '${familyData.head.name}' already exists.` });
}
// π Save to MongoDB
const newFamily = new Family(familyData);
await newFamily.save();
// π Create Excel File
const wb = xlsx.utils.book_new();
const ws_data = [['Relation', 'Name', 'DOB', 'Phone', 'Address']];
ws_data.push(['Head of Family', familyData.head.name, familyData.head.dob, familyData.head.phone, familyData.address]);
if (familyData.spouse) ws_data.push(['Spouse', familyData.spouse.name, familyData.spouse.dob, familyData.spouse.phone, familyData.address]);
if (familyData.sons) familyData.sons.forEach((son, index) => ws_data.push([`Son ${index + 1}`, son.name, son.dob, son.phone, familyData.address]));
if (familyData.daughters) familyData.daughters.forEach((daughter, index) => ws_data.push([`Daughter ${index + 1}`, daughter.name, daughter.dob, daughter.phone, familyData.address]));
if (familyData.father) ws_data.push(['Father', familyData.father.name, familyData.father.dob, familyData.father.phone, familyData.address]);
if (familyData.mother) ws_data.push(['Mother', familyData.mother.name, familyData.mother.dob, familyData.mother.phone, familyData.address]);
if (familyData.fatherInLaw) ws_data.push(['Father-in-Law', familyData.fatherInLaw.name, familyData.fatherInLaw.dob, familyData.fatherInLaw.phone, familyData.address]);
if (familyData.motherInLaw) ws_data.push(['Mother-in-Law', familyData.motherInLaw.name, familyData.motherInLaw.dob, familyData.motherInLaw.phone, familyData.address]);
const ws = xlsx.utils.aoa_to_sheet(ws_data);
xlsx.utils.book_append_sheet(wb, ws, familyData.head.name);
// π Save Excel Locally
const tempDir = './temp';
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
const filePath = path.join(tempDir, `${familyData.head.name}.xlsx`);
xlsx.writeFile(wb, filePath);
// βοΈ Upload Excel to Cloudinary
const result = await cloudinary.uploader.upload(filePath, {
folder: `${familyData.head.name}`,
resource_type: 'raw'
});
// ποΈ Delete Local Excel File
fs.unlinkSync(filePath);
// π Update MongoDB with Cloudinary Excel URL
newFamily.cloudinaryExcelUrl = result.secure_url;
await newFamily.save();
res.status(200).json({
message: 'β
Family data submitted, Excel file uploaded!',
cloudinaryUrl: result.secure_url,
});
} catch (err) {
console.error('β Error:', err);
res.status(500).json({ message: 'Failed to submit form' });
}
});
// π Start Server
app.listen(PORT, HOSTNAME, () => {
console.log(`β
Server running on http://localhost:${PORT}`);
});