-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver2.js
More file actions
395 lines (356 loc) · 11 KB
/
server2.js
File metadata and controls
395 lines (356 loc) · 11 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
'use strict'
const { Pool } = require('pg')
const express = require('express')
const cors = require('cors')
require('dotenv').config()
const app = express()
const PORT = process.env.SERVER_PORT || 5000
// PostgreSQL configuration
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false // Use this for RDS with SSL enabled
}
})
// Middleware
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static('public'))
const allowedOrigins = ['https://pokedex.ericlan.tz', 'http://localhost:3000']
app.use(
cors({
origin: allowedOrigins,
credentials: true
})
)
// Start the server
app.listen(PORT, () => {
console.log(`Server listening on port: ${PORT}`)
})
// Routes
// ---------- Pokémon Routes ----------
// Fetch all Pokémon
app.get('/pokemon', async (req, res) => {
const query = `
SELECT DISTINCT
p.id,
p.name,
s.name AS species,
array_agg(DISTINCT jsonb_build_object('id', m.id, 'name', m.name)) AS moves,
array_agg(DISTINCT jsonb_build_object('id', t.id, 'name', t.name, 'color', t.color)) AS type,
pb.hp,
pb.attack,
pb.defense,
pb.special_attack,
pb.special_defense,
pb.speed
FROM pokemon p
JOIN pokemon_moves pm ON p.id = pm.pokemon_id
JOIN moves m ON pm.move_id = m.id
JOIN pokemon_types pt ON p.id = pt.pokemon_id
JOIN types t ON t.id = pt.type_id
JOIN pokemon_base_stats pb ON p.id = pb.pokemon_id
JOIN species s ON s.id = p.species_id
GROUP BY p.id, s.name, p.name, pb.hp, pb.attack, pb.defense, pb.special_attack, pb.special_defense, pb.speed
ORDER BY p.id;
`
try {
const result = await pool.query(query)
res.json(result.rows)
} catch (err) {
console.error('Error fetching Pokémon:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Fetch Pokémon by ID
app.get('/pokemon/:id', async (req, res) => {
const { id } = req.params
const query = `
SELECT DISTINCT
p.id,
p.name,
s.name AS species,
array_agg(DISTINCT jsonb_build_object('id', m.id, 'name', m.name)) AS moves,
array_agg(DISTINCT jsonb_build_object('id', t.id, 'name', t.name, 'color', t.color)) AS type,
pb.hp,
pb.attack,
pb.defense,
pb.special_attack,
pb.special_defense,
pb.speed
FROM pokemon p
JOIN pokemon_moves pm ON p.id = pm.pokemon_id
JOIN moves m ON pm.move_id = m.id
JOIN pokemon_types pt ON p.id = pt.pokemon_id
JOIN types t ON t.id = pt.type_id
JOIN pokemon_base_stats pb ON p.id = pb.pokemon_id
JOIN species s ON s.id = p.species_id
WHERE p.id = $1
GROUP BY p.id, s.name, p.name, pb.hp, pb.attack, pb.defense, pb.special_attack, pb.special_defense, pb.speed
ORDER BY p.id;
`
try {
const result = await pool.query(query, [id])
res.json(result.rows)
} catch (err) {
console.error(`Error fetching Pokémon with ID ${id}:`, err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Add a new Pokémon
// Update Pokémon
app.put('/pokemon', async (req, res) => {
const { id, name, species_id, moves, type, height, weight, stats } = req.body
if (!id) return res.status(400).send({ error: 'ID is required' })
try {
await pool.query('BEGIN')
// Update Pokémon details
const pokemonQuery = `
UPDATE pokemon
SET name = $1, species_id = $2, height = $3, weight = $4
WHERE id = $5;
`
await pool.query(pokemonQuery, [name, species_id, height, weight, id])
// Update moves
if (moves) {
await pool.query('DELETE FROM pokemon_moves WHERE pokemon_id = $1;', [id])
const moveQueries = moves.map((moveId) =>
pool.query(
'INSERT INTO pokemon_moves (pokemon_id, move_id) VALUES ($1, $2);',
[id, moveId]
)
)
await Promise.all(moveQueries)
}
// Update types
if (type) {
await pool.query('DELETE FROM pokemon_types WHERE pokemon_id = $1;', [id])
const typeQueries = type.map((typeId) =>
pool.query(
'INSERT INTO pokemon_types (pokemon_id, type_id) VALUES ($1, $2);',
[id, typeId]
)
)
await Promise.all(typeQueries)
}
// Update stats
if (stats) {
const statsQuery = `
UPDATE pokemon_base_stats
SET hp = $1, attack = $2, defense = $3, special_attack = $4, special_defense = $5, speed = $6
WHERE pokemon_id = $7;
`
await pool.query(statsQuery, [
stats.hp,
stats.attack,
stats.defense,
stats.special_attack,
stats.special_defense,
stats.speed,
id
])
}
await pool.query('COMMIT')
res.status(200).send({ message: 'Pokémon updated successfully!' })
} catch (err) {
await pool.query('ROLLBACK')
console.error('Error updating Pokémon:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Delete Pokémon
app.delete('/pokemon/:id', async (req, res) => {
const { id } = req.params
try {
await pool.query('BEGIN')
await pool.query('DELETE FROM pokemon_moves WHERE pokemon_id = $1;', [id])
await pool.query('DELETE FROM pokemon_types WHERE pokemon_id = $1;', [id])
await pool.query('DELETE FROM pokemon_base_stats WHERE pokemon_id = $1;', [
id
])
await pool.query('DELETE FROM pokemon WHERE id = $1;', [id])
await pool.query('COMMIT')
res.status(200).send({ message: 'Pokémon deleted successfully!' })
} catch (err) {
await pool.query('ROLLBACK')
console.error('Error deleting Pokémon:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// ---------- Moves Routes ----------
// Fetch all moves
app.get('/moves', async (req, res) => {
const query = 'SELECT id, name FROM moves'
try {
const result = await pool.query(query)
res.json(result.rows)
} catch (err) {
console.error('Error fetching moves:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Fetch move details by ID
app.get('/moves/:id', async (req, res) => {
const { id } = req.params
const query = `
SELECT m.id, m.name AS move_name, t.name AS type_name, m.power, m.accuracy, m.power_point
FROM moves m
JOIN types t ON m.types_id = t.id
WHERE m.id = $1;
`
try {
const result = await pool.query(query, [id])
res.json(result.rows)
} catch (err) {
console.error(`Error fetching move with ID ${id}:`, err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Add a new move
app.post('/moves', async (req, res) => {
const { name, types_id, power, accuracy, power_point } = req.body
const query = `
INSERT INTO moves (name, types_id, power, accuracy, power_point)
VALUES ($1, $2, $3, $4, $5);
`
try {
await pool.query(query, [name, types_id, power, accuracy, power_point])
res.status(201).send({ message: 'Move added successfully!' })
} catch (err) {
console.error('Error adding move:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Update move
app.put('/moves/:id', async (req, res) => {
const { id } = req.params
const { name, types_id, power, accuracy, power_point } = req.body
const query = `
UPDATE moves
SET name = $1, types_id = $2, power = $3, accuracy = $4, power_point = $5
WHERE id = $6;
`
try {
await pool.query(query, [name, types_id, power, accuracy, power_point, id])
res.status(200).send({ message: 'Move updated successfully!' })
} catch (err) {
console.error('Error updating move:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Delete move
app.delete('/moves/:id', async (req, res) => {
const { id } = req.params
const query = 'DELETE FROM moves WHERE id = $1;'
try {
await pool.query(query, [id])
res.status(200).send({ message: 'Move deleted successfully!' })
} catch (err) {
console.error('Error deleting move:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// ---------- Types Routes ----------
// Fetch all types
app.get('/types', async (req, res) => {
const query = 'SELECT id, name, color FROM types'
try {
const result = await pool.query(query)
res.json(result.rows)
} catch (err) {
console.error('Error fetching types:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Fetch type details by ID
app.get('/types/:id', async (req, res) => {
const { id } = req.params
const query = `
SELECT t.name, te.attacking_type_id, te.defending_type_id, te.effectiveness
FROM types t
JOIN type_effectiveness te
ON t.id = te.attacking_type_id
OR t.id = te.defending_type_id
WHERE t.id = $1;
`
try {
const result = await pool.query(query, [id])
res.json(result.rows)
} catch (err) {
console.error(`Error fetching type with ID ${id}:`, err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Add a new type
app.post('/types', async (req, res) => {
const { name, color } = req.body
const query = `
INSERT INTO types (name, color)
VALUES ($1, $2);
`
try {
await pool.query(query, [name, color])
res.status(201).send({ message: 'Type added successfully!' })
} catch (err) {
console.error('Error adding type:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Update type
app.put('/types/:id', async (req, res) => {
const { id } = req.params
const { name, color } = req.body
const query = `
UPDATE types
SET name = $1, color = $2
WHERE id = $3;
`
try {
await pool.query(query, [name, color, id])
res.status(200).send({ message: 'Type updated successfully!' })
} catch (err) {
console.error('Error updating type:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Delete type
app.delete('/types/:id', async (req, res) => {
const { id } = req.params
const query = 'DELETE FROM types WHERE id = $1;'
try {
await pool.query(query, [id])
res.status(200).send({ message: 'Type deleted successfully!' })
} catch (err) {
console.error('Error deleting type:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// ---------- Species Routes ----------
// Fetch all species
app.get('/species', async (req, res) => {
const query = 'SELECT id, name FROM species ORDER BY id;'
try {
const result = await pool.query(query)
res.json(result.rows)
} catch (err) {
console.error('Error fetching species:', err)
res.status(500).send({ error: 'Internal server error' })
}
})
// Fetch species by ID
app.get('/species/:id', async (req, res) => {
const { id } = req.params
const query = 'SELECT id, name FROM species WHERE id = $1;'
try {
const result = await pool.query(query, [id])
if (result.rows.length === 0) {
res.status(404).send({ error: 'Species not found' })
} else {
res.json(result.rows[0])
}
} catch (err) {
console.error(`Error fetching species with ID ${id}:`, err)
res.status(500).send({ error: 'Internal server error' })
}
})
module.exports = app