-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
101 lines (84 loc) · 3.01 KB
/
Copy pathserver.js
File metadata and controls
101 lines (84 loc) · 3.01 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
require('dotenv').config();
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const mysql = require('mysql2/promise');
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Config
app.use(cors());
app.use(express.json());
app.use(express.static(__dirname));
// Multer memory storage (buffer files in memory before S3 upload)
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
// AWS S3 Configuration
const s3Client = new S3Client({
region: process.env.AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
}
});
const BUCKET_NAME = process.env.S3_BUCKET_NAME;
// Database Connection Pool
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// --- API ROUTES ---
// GET all notes from MySQL
app.get('/api/notes', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM notes ORDER BY upload_date DESC');
res.json(rows);
} catch (error) {
console.error('Database connection or query error:', error);
res.status(500).json({ error: 'Failed to fetch notes from database' });
}
});
// POST a new note (Upload to S3, save to MySQL)
app.post('/api/upload', upload.single('file'), async (req, res) => {
try {
const { title, subject } = req.body;
const file = req.file;
if (!title || !subject || !file) {
return res.status(400).json({ error: 'Title, subject, and file are required.' });
}
// 1. Upload to AWS S3
const objectKey = `uploads/${Date.now()}-${file.originalname.replace(/\s+/g, '_')}`;
const putObjectParams = {
Bucket: BUCKET_NAME,
Key: objectKey,
Body: file.buffer,
ContentType: file.mimetype
};
const command = new PutObjectCommand(putObjectParams);
await s3Client.send(command);
// 2. Construct public S3 URL
const fileUrl = `https://${BUCKET_NAME}.s3.${process.env.AWS_REGION}.amazonaws.com/${objectKey}`;
// 3. Save to MySQL (AWS RDS)
const query = 'INSERT INTO notes (title, subject, file_url) VALUES (?, ?, ?)';
const [result] = await pool.execute(query, [title, subject, fileUrl]);
res.status(201).json({
id: result.insertId,
title,
subject,
file_url: fileUrl
});
} catch (error) {
console.error('Failed to upload file or save to database:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});