-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
208 lines (175 loc) · 6.53 KB
/
Copy pathindex.js
File metadata and controls
208 lines (175 loc) · 6.53 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
const express = require('express');
const priceReceiver = require('./pricereceiver.js');
const fs = require('fs');
const cors = require('cors'); // Import CORS middleware
const { Pool } = require('pg');
const path = require('path');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'pokecollection',
password: 'postgres',
port: 5432,
});
const app = express();
const port = 3000;
// const pokemonSet = 'pokemon-journey-together';
// const pokemonName = 'n%27s-reshiram-167';
let SetURLS = {};
const imageCache = {}; // In-memory cache for image links
app.use(express.json());
app.use(cors()); // Enable CORS for all routes
app.use(express.static(path.join(__dirname, 'public'))); // Serve static files from the "public" directory
app.get('/', (req, res) => {
console.log("Server root accessed");
res.sendFile(__dirname + '/public/index.html');
});
app.get('/cardPrice', (req, res) => {
const { pokemonSet, pokemonName } = req.query; // Extract query parameters
console.log(`Fetching price for set: ${pokemonSet}, card: ${pokemonName}`);
const price = priceReceiver.getPrice(pokemonSet, pokemonName);
price.then(price => {
res.send(price);
}).catch(err => {
console.error('Error fetching price:', err);
res.status(500).send("Error fetching price");
});
});
app.get('/images', (req, res) => {
// let msg = "";
// for (const [key, value] of Object.entries(SetURLS)) {
// msg += `${key}: ${value}`;
// }
// console.log(msg);
res.send(SetURLS);
});
app.get('/give/:SetName', (req, res) => {
const name = req.params.SetName.replace(/-/g, ' ').toLowerCase();
console.log(`Fetching card details for set: ${name}`);
// Check if the card details for the set are already cached
if (imageCache[name]) {
console.log(`Using cached card details for set: ${name}`);
res.json(imageCache[name]); // Return cached card details
return;
}
if (!SetURLS[name]) {
console.error(`SetName "${name}" not found in SetURLS`);
res.status(404).send(`Error: SetName "${name}" not found`);
return;
}
const url = SetURLS[name].url;
const cardDetailsPromise = priceReceiver.getPokemonImages(url);
console.log("Fetching card details for set: " + name + " from URL: " + url);
cardDetailsPromise.then(cardDetails => {
imageCache[name] = cardDetails; // Cache the fetched card details
res.json(cardDetails); // Return the card details as JSON
}).catch(err => {
console.error('Error fetching card details:', err);
res.status(500).send("Error fetching card details");
});
});
app.get('/seturls', async (req, res) => {
SetURLS = await priceReceiver.PopulateSetURLS()
console.log("loaded SetURLS: ", SetURLS);
});
app.get('/card/:CardId', (req, res) => {
const cardId = req.params.CardId;
console.log(`Fetching details for card: ${cardId}`);
// Mock data for demonstration purposes
const cardDetails = {
image: `https://example.com/cards/${cardId}.png`,
price: Math.random() * 100, // Random price for demonstration
};
res.json(cardDetails);
});
// Endpoint to add or update card data
app.post('/updateCollection', async (req, res) => {
const {
userId,
setName,
cardName,
cardNumber,
basePrice,
reversePrice,
pokeBallPrice,
masterBallPrice,
baseQuantity,
reverseQuantity,
pokeBallQuantity,
masterBallQuantity,
} = req.body;
console.log(`\nUpdating collection for user ID: ${userId}, set: ${setName}, card: ${cardName}, number: ${cardNumber}`);
try {
const query = `
INSERT INTO card_collection (user_id, set_name, card_name, card_number, base_price, reverse_price, poke_ball_price, master_ball_price, base_quantity, reverse_quantity, poke_ball_quantity, master_ball_quantity)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
ON CONFLICT (user_id, set_name, card_name, card_number)
DO UPDATE SET
base_price = $5,
reverse_price = $6,
poke_ball_price = $7,
master_ball_price = $8,
base_quantity = $9,
reverse_quantity = $10,
poke_ball_quantity = $11,
master_ball_quantity = $12;
`;
const values = [
userId,
setName,
cardName,
cardNumber,
basePrice,
reversePrice,
pokeBallPrice,
masterBallPrice,
baseQuantity,
reverseQuantity,
pokeBallQuantity,
masterBallQuantity,
];
await pool.query(query, values);
res.status(200).send('Collection updated successfully');
} catch (error) {
console.error('Error updating collection:', error);
res.status(500).send('Error updating collection');
}
});
app.get('/getCollection/:userId', async (req, res) => {
const { userId } = req.params;
console.log(`Fetching collection for user ID: ${userId}`);
try {
const query = 'SELECT * FROM card_collection WHERE user_id = $1';
const values = [userId];
const result = await pool.query(query, values);
res.status(200).json(result.rows);
} catch (error) {
console.error('Error fetching collection:', error);
res.status(500).send('Error fetching collection');
}
});
app.get('/getCard', async (req, res) => {
const { setName, cardId } = req.query;
console.log(`\nFetching card details for set: ${setName}, card ID: ${cardId}\n`);
try {
const query = `SELECT * FROM card_collection WHERE set_name = $1 AND card_number = $2`;
const values = [setName, cardId];
const result = await pool.query(query, values);
if (result.rows.length > 0) {
res.status(200).json(result.rows[0]);
} else {
res.status(404).send('Card not found');
}
} catch (error) {
console.error('Error fetching card details:', error);
res.status(500).send('Error fetching card details');
}
});
app.listen(port, async () => {
console.log(`Example app listening at http://localhost:${port}`);
SetURLS = await priceReceiver.PopulateSetURLS()
// // Write the JSON to a file
// fs.writeFileSync('SetURLS.json', JSON.stringify(SetURLS, null, 2), 'utf-8');
// console.log("SetURLS saved to SetURLS.json");
console.log("loaded SetURLS: ", SetURLS);
});