-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
245 lines (220 loc) · 6.62 KB
/
server.js
File metadata and controls
245 lines (220 loc) · 6.62 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/**
* @swagger
* openapi: 3.0.0
* info:
* title: Travel API
* description: API documentation for the Travel Logger project
* version: 1.0.0
* servers:
* - url: http://localhost:3000
* paths:
* /api/destinations:
* get:
* summary: Get all destinations
* responses:
* 200:
* description: A list of destinations
* post:
* summary: Add a new destination
* requestBody:
* content:
* multipart/form-data:
* schema:
* type: object
* properties:
* place:
* type: string
* date_of_visit:
* type: string
* photos:
* type: array
* items:
* type: string
* format: binary
* responses:
* 200:
* description: Destination added successfully
* /api/destinations/{id}:
* get:
* summary: Get a specific destination by ID
* parameters:
* - name: id
* in: path
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Destination details
* put:
* summary: Update a destination by ID
* parameters:
* - name: id
* in: path
* required: true
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* place:
* type: string
* date_of_visit:
* type: string
* responses:
* 200:
* description: Destination updated successfully
* delete:
* summary: Delete a destination by ID
* parameters:
* - name: id
* in: path
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Destination deleted successfully
*/
const express = require('express');
const app = express();
const mysql = require('mysql2/promise');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Swagger setup
const swaggerSpec = swaggerJsdoc({
definition: {
openapi: '3.0.0',
info: {
title: 'Travel API',
version: '1.0.0',
description: 'API documentation for the Travel Logger project',
},
servers: [
{
url: 'http://localhost:3000',
},
],
},
apis: ['./server.js'],
});
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// Static files
app.use(express.static('public'));
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));
// Ensure upload folder exists
const uploadDir = path.join(__dirname, 'public/uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
// MySQL connection
const db = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'mydb@123',
database: 'travel_log'
});
// Multer setup
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public/uploads/');
},
filename: (req, file, cb) => {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage });
// Routes
app.post('/api/destinations', upload.array('photos'), async (req, res) => {
try {
const { place, date_of_visit } = req.body;
if (!place || !date_of_visit) {
return res.status(400).json({ message: 'Place and Date of Visit are required' });
}
const photoPaths = req.files.map(file => file.filename).join(',');
await db.query(
'INSERT INTO destinations (place, date_of_visit, photos) VALUES (?, ?, ?)',
[place, date_of_visit, photoPaths]
);
res.json({ message: 'Destination added successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Error adding destination' });
}
});
app.get('/api/destinations', async (req, res) => {
try {
const [rows] = await db.query('SELECT * FROM destinations ORDER BY id DESC');
res.json(rows);
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Error fetching destinations' });
}
});
app.get('/api/destinations/:id', async (req, res) => {
try {
const { id } = req.params;
const [rows] = await db.query('SELECT * FROM destinations WHERE id = ?', [id]);
if (rows.length === 0) return res.status(404).json({ message: 'Destination not found' });
const destination = rows[0];
destination.photos = destination.photos ? destination.photos.split(',') : [];
destination.photos = destination.photos.map(p => `/uploads/${p}`);
res.json(destination);
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Error fetching destination' });
}
});
app.put('/api/destinations/:id', async (req, res) => {
try {
const { id } = req.params;
const { place, date_of_visit } = req.body;
if (!place || !date_of_visit) {
return res.status(400).json({ message: 'Place and Date of Visit are required' });
}
await db.query(
'UPDATE destinations SET place = ?, date_of_visit = ? WHERE id = ?',
[place, date_of_visit, id]
);
res.json({ message: 'Destination updated successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Error updating destination' });
}
});
app.delete('/api/destinations/:id', async (req, res) => {
try {
const { id } = req.params;
const [rows] = await db.query('SELECT photos FROM destinations WHERE id = ?', [id]);
if (rows.length && rows[0].photos) {
const photos = rows[0].photos.split(',');
photos.forEach(photo => {
const photoPath = path.join(__dirname, 'public/uploads', photo);
if (fs.existsSync(photoPath)) fs.unlinkSync(photoPath);
});
}
await db.query('DELETE FROM destinations WHERE id = ?', [id]);
res.json({ message: 'Destination deleted successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Error deleting destination' });
}
});
// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, 'localhost', () => {
console.log(`🚀 Server running at http://localhost:${PORT}`);
});
module.exports = app;