← back to Costa Rica
scripts/ingest/region-images-fallback.js
49 lines
'use strict';
// For regions without an image, fall back to the province image.
const { fetchJson, sleep, pool } = require('./_lib');
const PROVINCE_TITLES = {
'San José': 'San_José_Province',
'Alajuela': 'Alajuela_Province',
'Heredia': 'Heredia_Province',
'Cartago': 'Cartago_Province',
'Limón': 'Limón_Province',
'Puntarenas': 'Puntarenas_Province',
'Guanacaste': 'Guanacaste_Province',
};
(async () => {
const cache = {};
for (const [prov, title] of Object.entries(PROVINCE_TITLES)) {
try {
const j = await fetchJson(`https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(title)}`,
{ headers: { 'Api-User-Agent': 'CR-Directory/0.1 (info@agentabrams.com)' } });
const img = (j.originalimage || j.thumbnail);
if (img) cache[prov] = {
url: img.source,
credit: `Wikipedia: ${j.title}`,
source_url: j.content_urls?.desktop?.page || `https://en.wikipedia.org/wiki/${encodeURIComponent(title)}`,
};
console.log(`[prov] ${prov} → ${img ? 'HIT' : 'miss'}`);
await sleep(400);
} catch (e) { console.warn(`[prov] ${prov} err: ${e.message}`); }
}
const { rows } = await pool.query(
`SELECT id, slug, name, province FROM regions WHERE region_type IN ('city','town','canton') AND image_url IS NULL`
);
let n = 0;
for (const r of rows) {
const fallback = cache[r.province];
if (!fallback) continue;
await pool.query(
`UPDATE regions SET image_url=$1, image_credit=$2, image_license='CC via Wikimedia Commons',
image_source_url=$3, image_fetched_at=NOW() WHERE id=$4`,
[fallback.url, fallback.credit + ' (province fallback)', fallback.source_url, r.id]
);
n++;
}
console.log(`[fallback] applied province image to ${n} regions`);
await pool.end();
})();