Extract shared import logic into lib/card-import, discover missing sets via Scryfall/Pokémon TCG APIs, and expose GET /api/cron/sync-catalog protected by CRON_SECRET (max 3 sets/run, paced imports). Co-authored-by: Cursor <cursoragent@cursor.com>
69 lines
2.1 KiB
JavaScript
69 lines
2.1 KiB
JavaScript
import { discoverMissingMtgSets, discoverMissingPokemonSets } from './discover.js';
|
|
import { importMtgSet } from './mtg.js';
|
|
import { importPokemonSet } from './pokemon.js';
|
|
|
|
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
|
|
const DEFAULT_MAX_SETS_PER_RUN = 3;
|
|
const DEFAULT_DELAY_MS = 1500;
|
|
|
|
/**
|
|
* Discover missing MTG + Pokémon sets and import up to maxSetsPerRun, paced for upstream APIs.
|
|
*/
|
|
export async function runCatalogSync(options = {}) {
|
|
const maxSetsPerRun = options.maxSetsPerRun ?? DEFAULT_MAX_SETS_PER_RUN;
|
|
const delayBetweenSetsMs = options.delayBetweenSetsMs ?? DEFAULT_DELAY_MS;
|
|
|
|
const [missingMtg, missingPokemon] = await Promise.all([
|
|
discoverMissingMtgSets(),
|
|
discoverMissingPokemonSets(),
|
|
]);
|
|
|
|
const queue = [
|
|
...missingMtg.map((set) => ({ game: 'mtg', setCode: set.code, name: set.name })),
|
|
...missingPokemon.map((set) => ({ game: 'pokemon', setCode: set.id, name: set.name })),
|
|
].slice(0, maxSetsPerRun);
|
|
|
|
const summary = {
|
|
imported: 0,
|
|
skipped: 0,
|
|
errors: [],
|
|
setsProcessed: [],
|
|
pendingMtgSets: missingMtg.length,
|
|
pendingPokemonSets: missingPokemon.length,
|
|
lorcana: 'skipped — manual Lorcana set map update required',
|
|
};
|
|
|
|
for (let index = 0; index < queue.length; index += 1) {
|
|
const item = queue[index];
|
|
try {
|
|
const result =
|
|
item.game === 'mtg'
|
|
? await importMtgSet(item.setCode)
|
|
: await importPokemonSet(item.setCode);
|
|
|
|
summary.setsProcessed.push({
|
|
game: item.game,
|
|
setCode: item.setCode,
|
|
name: item.name,
|
|
...result,
|
|
});
|
|
summary.imported += result.imported;
|
|
summary.skipped += result.skipped;
|
|
} catch (error) {
|
|
console.error(`[runCatalogSync] Failed ${item.game}/${item.setCode}:`, error);
|
|
summary.errors.push({
|
|
game: item.game,
|
|
setCode: item.setCode,
|
|
message: error.message,
|
|
});
|
|
}
|
|
|
|
if (index < queue.length - 1) {
|
|
await delay(delayBetweenSetsMs);
|
|
}
|
|
}
|
|
|
|
console.log('[runCatalogSync]', JSON.stringify(summary));
|
|
return summary;
|
|
}
|