-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·153 lines (128 loc) · 3.91 KB
/
Copy pathserver.js
File metadata and controls
executable file
·153 lines (128 loc) · 3.91 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
const express = require('express');
const { Pool } = require('pg');
const redis = require('redis');
const ejs = require('ejs');
const app = express();
const port = process.env.PORT || 3000;
// PostgreSQL configuration
const pgPool = new Pool({
user: process.env.PG_USER,
host: process.env.PG_HOST || 'postgresql',
database: process.env.PG_DATABASE,
password: process.env.PG_PASSWORD,
port: process.env.PG_PORT || 5432,
});
// Redis configuration
const redisClient = redis.createClient({
host: process.env.REDIS_HOST || 'redis',
port: process.env.REDIS_PORT || 6379,
password: process.env.REDIS_PASSWORD,
});
async function connectToDatabase() {
try {
const client = await pgPool.connect();
console.log('Connected to database successfully');
client.release();
} catch (error) {
console.error('Failed to connect to the database', error);
throw new Error('Database connection failed');
}
}
connectToDatabase().catch(error => {
console.error('Error:', error.message);
});
redisClient.on('connect', () => {
console.log('Connected to Redis');
});
redisClient.on('error', (rderr) => {
console.error('Redis Cache Connection Error:', rderr);
});
// Middleware to parse JSON requests
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Set EJS as the view engine
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
// Routes
app.get('/json', async (req, res) => {
try {
// Check if data is in Redis cache
const cachedUsers = await getCachedUsers();
if (cachedUsers) {
console.log('Data retrieved from Redis cache');
res.json({ users: cachedUsers, source: 'Redis' });
} else {
// If not in cache, retrieve from PostgreSQL and store in Redis
const result = await pgPool.query('SELECT * FROM users');
const users = result.rows;
console.log('Data retrieved from PostgreSQL');
// Store data in Redis cache
setCachedUsers(users);
res.json({ users, source: 'PostgreSQL' });
}
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
// Helper function to get data from Redis cache
async function getCachedUsers() {
return new Promise((resolve, reject) => {
redisClient.get('users', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data ? JSON.parse(data) : null);
}
});
});
}
// Helper function to set data in Redis cache
function setCachedUsers(users) {
redisClient.set('users', JSON.stringify(users));
}
// Routes
app.get('/', async (req, res) => {
try {
const result = await pgPool.query('SELECT * FROM users');
const users = result.rows;
res.render('index', { users });
} catch (error) {
console.error('PostgreSQL Error:', error);
res.status(500).send('Internal Server Error');
}
});
app.post('/users', async (req, res) => {
const { name, email } = req.body;
try {
const result = await pgPool.query('INSERT INTO users(name, email) VALUES($1, $2) RETURNING *', [name, email]);
const newUser = result.rows[0];
// Clear Redis cache after adding a new user
redisClient.del('users');
res.redirect('/');
} catch (error) {
console.error('PostgreSQL Error:', error);
res.status(500).send('Internal Server Error');
}
});
app.post('/users/delete/:id', async (req, res) => {
const userId = req.params.id;
try {
await pgPool.query('DELETE FROM users WHERE id = $1', [userId]);
// Clear Redis cache after deleting a user
redisClient.del('users');
res.redirect('/');
} catch (error) {
console.error('PostgreSQL Error:', error);
res.status(500).send('Internal Server Error');
}
});
// Handle invalid routes
app.use((req, res) => {
res.status(404).send('Not Found');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});