-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
237 lines (207 loc) · 6.63 KB
/
server.js
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
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const AWS = require('aws-sdk');
const app = express();
const port = 3001;
app.use(cors());
app.use(bodyParser.json());
let currentConnection;
let isConnected = false;
function createConnection(host) {
return mysql.createConnection({
host: host,
user: 'username', // replace with your MySQL user
password: 'password', // replace with your MySQL password
database: 'AlightDisasterRecoveryDemo', // replace with your database name
});
}
function connectToDatabase(host) {
return new Promise((resolve, reject) => {
if (currentConnection) {
currentConnection.end((err) => {
if (err) {
console.error('Error closing previous database connection:', err);
}
});
}
currentConnection = createConnection(host);
currentConnection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err);
isConnected = false;
reject(err);
} else {
console.log('Successfully connected to the database.');
isConnected = true;
resolve();
}
});
});
}
app.post('/change-host', async (req, res) => {
isConnected = false;
const newHost = req.body.host;
if (!newHost) {
return res.status(400).send('Host is required');
}
try {
await connectToDatabase(newHost);
res.send(`Successfully reconnected to new host: ${newHost}`);
} catch (error) {
console.error(`Error reconnecting to new host ${newHost}:`, error);
res.status(500).send(`Error reconnecting: ${error.message}`);
}
});
app.get('/connection-details', (req, res) => {
res.json({
host: currentConnection ? currentConnection.config.host : 'Not connected',
status: isConnected ? 'Connected' : 'Not connected',
});
});
app.get('/list-rds-instances', async (req, res) => {
const region = req.query.region;
AWS.config.update({ region });
const rds = new AWS.RDS();
try {
const data = await rds.describeDBInstances().promise();
res.json(data.DBInstances);
} catch (err) {
console.error('Error listing RDS instances in region', region, ':', err);
res.status(500).send(err.message);
}
});
// MYSQL API endpoints
async function executeQuery(sql, params = []) {
if (!currentConnection || !isConnected) {
console.error('Database reconnection failed:', reconnectError);
throw new Error(
}
return new Promise((resolve, reject) => {
currentConnection.query(sql, params, (err, result) => {
if (err) {
console.error('Database query error:', err);
isConnected = false;
reject(err);
} else {
resolve(result);
}
});
});
}
app.post('/users', async (req, res) => {
const user = req.body;
const sql = 'INSERT INTO users SET ?';
try {
await executeQuery(sql, user);
res.send('User added successfully!');
} catch (err) {
console.error('Error adding user:', err);
res.status(500).send('Error adding user');
}
});
app.get('/users', async (req, res) => {
const sql = 'SELECT * FROM users';
try {
const results = await executeQuery(sql);
res.json(results);
} catch (err) {
console.error('Error fetching users:', err);
res.status(500).send('Error fetching users');
}
});
app.put('/users/:id', async (req, res) => {
const userId = req.params.id;
const user = req.body;
const sql = 'UPDATE users SET ? WHERE id = ?';
try {
await executeQuery(sql, [user, userId]);
res.send('User updated successfully!');
} catch (err) {
console.error('Error updating user:', err);
res.status(500).send('Error updating user');
}
});
app.delete('/users/:id', async (req, res) => {
const userId = req.params.id;
const sql = 'DELETE FROM users WHERE id = ?';
try {
await executeQuery(sql, [userId]);
res.send('User deleted successfully!');
} catch (err) {
console.error('Error deleting user:', err);
res.status(500).send('Error deleting user');
}
});
app.get('/create-users-table', async (req, res) => {
try {
await createDatabaseTable();
res.send('Users table created or already exists');
} catch (err) {
console.error('Error creating users table:', err);
res.status(500).send('Error creating users table');
}
});
function createDatabaseTable() {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`;
return new Promise((resolve, reject) => {
currentConnection.query(createTableQuery, (error, results, fields) => {
if (error) {
console.error('Error creating table:', error);
reject(error);
} else {
console.log('Table created or already exists');
resolve();
}
});
});
}
app.get('/', (req, res) => {
res.status(200).send('Express app is running!');
});
app.get('/api/region', async (req, res) => {
try {
const response = await fetchRegion();
res.send(response);
} catch (error) {
if (error.response === undefined || error.response.status === 404) {
res.status(200).send('Running locally');
} else {
res.status(500).send('Error fetching region');
}
}
});
async function fetchRegion() {
try {
const tokenResponse = await axios.put('http://169.254.169.254/latest/api/token', null, {
headers: {
'X-aws-ec2-metadata-token-ttl-seconds': '21600',
},
});
const token = tokenResponse.data;
const azResponse = await axios.get(
'http://169.254.169.254/latest/meta-data/placement/availability-zone',
{
headers: {
'X-aws-ec2-metadata-token': token,
},
},
);
const region = azResponse.data.slice(0, -1);
return region;
} catch (error) {
throw error;
}
}
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});