2026-05-27 15:59:59 -04:00
|
|
|
import { sql } from '@vercel/postgres';
|
|
|
|
|
|
2026-05-28 12:44:49 -04:00
|
|
|
import {
|
|
|
|
|
fetchPokemonSetCards,
|
|
|
|
|
fetchPokemonSets,
|
|
|
|
|
mapGithubCardForInsert,
|
|
|
|
|
} from './pokemon-github.js';
|
2026-05-27 15:59:59 -04:00
|
|
|
|
2026-05-28 12:44:49 -04:00
|
|
|
export { fetchWithRetry, fetchPokemonSets } from './pokemon-github.js';
|
2026-05-27 15:59:59 -04:00
|
|
|
|
|
|
|
|
/**
|
2026-05-28 12:44:49 -04:00
|
|
|
* Import all cards for a Pokémon set id from the pokemon-tcg-data GitHub repo.
|
|
|
|
|
* Skips rows already present by scryfall_id (legacy column name stores external card ids).
|
2026-05-27 15:59:59 -04:00
|
|
|
*/
|
|
|
|
|
export async function importPokemonSet(setCode) {
|
2026-05-28 12:44:49 -04:00
|
|
|
const [sets, cards] = await Promise.all([
|
|
|
|
|
fetchPokemonSets(),
|
|
|
|
|
fetchPokemonSetCards(setCode),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
const setMeta = sets.find((set) => set.id?.toLowerCase() === setCode.toLowerCase()) || {
|
|
|
|
|
id: setCode,
|
|
|
|
|
name: setCode,
|
|
|
|
|
};
|
2026-05-27 15:59:59 -04:00
|
|
|
|
|
|
|
|
if (cards.length === 0) {
|
|
|
|
|
return { setCode, imported: 0, skipped: 0, total: 0 };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let imported = 0;
|
|
|
|
|
let skipped = 0;
|
|
|
|
|
|
|
|
|
|
for (const card of cards) {
|
|
|
|
|
try {
|
2026-05-28 12:44:49 -04:00
|
|
|
const mapped = mapGithubCardForInsert(card, setMeta);
|
|
|
|
|
|
2026-05-27 15:59:59 -04:00
|
|
|
const existingCard = await sql`
|
2026-05-28 12:44:49 -04:00
|
|
|
SELECT id FROM cards WHERE scryfall_id = ${mapped.externalId}
|
2026-05-27 15:59:59 -04:00
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
if (existingCard.rows.length > 0) {
|
|
|
|
|
skipped += 1;
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await sql`
|
|
|
|
|
INSERT INTO cards (
|
|
|
|
|
name, set_name, set_code, card_number, rarity, game,
|
|
|
|
|
mana_cost, cmc, card_type, colors, oracle_text,
|
|
|
|
|
power, toughness, image_url, stock_image_url,
|
|
|
|
|
current_price, market_price, scryfall_id, verified
|
|
|
|
|
) VALUES (
|
2026-05-28 12:44:49 -04:00
|
|
|
${mapped.name}, ${mapped.setName}, ${mapped.setCode}, ${mapped.cardNumber},
|
|
|
|
|
${mapped.rarity}, 'Pokemon', null, null, ${mapped.cardType},
|
|
|
|
|
${JSON.stringify(mapped.types)}, ${mapped.flavorText},
|
|
|
|
|
${mapped.hp}, null,
|
|
|
|
|
${mapped.imageSmall}, ${mapped.imageLarge},
|
|
|
|
|
null, null, ${mapped.externalId}, true
|
2026-05-27 15:59:59 -04:00
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
imported += 1;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(`[importPokemonSet] Error importing card ${card.name}:`, error);
|
|
|
|
|
skipped += 1;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { setCode, imported, skipped, total: cards.length };
|
|
|
|
|
}
|