174 lines
6.6 KiB
JavaScript
174 lines
6.6 KiB
JavaScript
"use strict";
|
|
/**
|
|
|
|
* Country catalog: sync from REST Countries v5 (optional API key) or ISO 3166 fallback.
|
|
|
|
*/
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || (function () {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
var ar = [];
|
|
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
})();
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.CountryBlockedError = void 0;
|
|
exports.syncCountriesFromApi = syncCountriesFromApi;
|
|
exports.ensureCountriesSeeded = ensureCountriesSeeded;
|
|
exports.assertCountryAllowedForRegistration = assertCountryAllowedForRegistration;
|
|
exports.listRegistrationCountries = listRegistrationCountries;
|
|
exports.listAllCountriesAdmin = listAllCountriesAdmin;
|
|
exports.setCountryRegistrationAllowed = setCountryRegistrationAllowed;
|
|
const config_1 = require("../config");
|
|
const countryRepository = __importStar(require("../repositories/countryRepository"));
|
|
const countryFormat_1 = require("../utils/countryFormat");
|
|
const REST_COUNTRIES_V5_URL = 'https://api.restcountries.com/countries/v5';
|
|
const ISO_COUNTRIES_URL = 'https://raw.githubusercontent.com/lukes/ISO-3166-Countries-with-Regional-Codes/master/all/all.json';
|
|
class CountryBlockedError extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
this.name = 'CountryBlockedError';
|
|
}
|
|
}
|
|
exports.CountryBlockedError = CountryBlockedError;
|
|
async function fetchFromRestCountriesV5(apiKey) {
|
|
const items = [];
|
|
let offset = 0;
|
|
const limit = 100;
|
|
while (true) {
|
|
const url = `${REST_COUNTRIES_V5_URL}?limit=${limit}&offset=${offset}&response_fields=names.common,codes.alpha_2`;
|
|
const res = await fetch(url, {
|
|
headers: {
|
|
Accept: 'application/json',
|
|
Authorization: `Bearer ${apiKey}`,
|
|
},
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`REST Countries v5 request failed (${res.status})`);
|
|
}
|
|
const body = (await res.json());
|
|
if (body.errors?.length) {
|
|
throw new Error(body.errors.map((e) => e.message).join('; '));
|
|
}
|
|
if (body.data?._demo) {
|
|
throw new Error('REST Countries demo key cannot sync the full catalog. Set a real REST_COUNTRIES_API_KEY or leave it unset to use the ISO 3166 fallback.');
|
|
}
|
|
for (const country of body.data?.objects ?? []) {
|
|
const code = country.codes?.alpha_2;
|
|
const name = country.names?.common;
|
|
if (code && name) {
|
|
items.push({ code: code.toUpperCase(), name });
|
|
}
|
|
}
|
|
if (!body.data?.meta?.more)
|
|
break;
|
|
offset += limit;
|
|
}
|
|
return items;
|
|
}
|
|
async function fetchFromIso3166Fallback() {
|
|
const res = await fetch(ISO_COUNTRIES_URL, {
|
|
headers: { Accept: 'application/json' },
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`ISO 3166 country list fetch failed (${res.status})`);
|
|
}
|
|
const data = (await res.json());
|
|
if (!Array.isArray(data)) {
|
|
throw new Error('ISO 3166 country list returned an invalid payload');
|
|
}
|
|
return data
|
|
.filter((c) => c['alpha-2'] && c.name)
|
|
.map((c) => ({
|
|
code: c['alpha-2'].toUpperCase(),
|
|
name: c.name,
|
|
}));
|
|
}
|
|
async function syncCountriesFromApi() {
|
|
const apiKey = config_1.config.countries.restCountriesApiKey;
|
|
const items = apiKey
|
|
? await fetchFromRestCountriesV5(apiKey)
|
|
: await fetchFromIso3166Fallback();
|
|
const source = apiKey ? 'restcountries-v5' : 'iso-3166';
|
|
if (items.length === 0) {
|
|
throw new Error('No countries received from catalog source');
|
|
}
|
|
const synced = await countryRepository.upsertMany(items);
|
|
if (synced === 0) {
|
|
throw new Error('No countries were saved to the database');
|
|
}
|
|
(0, countryFormat_1.clearCountryNameCache)();
|
|
return { synced, source };
|
|
}
|
|
async function ensureCountriesSeeded() {
|
|
const n = await countryRepository.count();
|
|
if (n > 0)
|
|
return;
|
|
try {
|
|
const result = await syncCountriesFromApi();
|
|
console.log(`[countries] Initial catalog synced (${result.synced} countries from ${result.source})`);
|
|
}
|
|
catch (e) {
|
|
console.warn('[countries] Could not sync on startup:', e instanceof Error ? e.message : e);
|
|
}
|
|
}
|
|
async function assertCountryAllowedForRegistration(code) {
|
|
const normalized = code.trim().toUpperCase();
|
|
if (!/^[A-Z]{2}$/.test(normalized)) {
|
|
throw new CountryBlockedError('Invalid country code');
|
|
}
|
|
const total = await countryRepository.count();
|
|
if (total === 0)
|
|
return;
|
|
const allowed = await countryRepository.isRegistrationAllowed(normalized);
|
|
if (!allowed) {
|
|
throw new CountryBlockedError('Registration is not available for this country of residence');
|
|
}
|
|
}
|
|
async function listRegistrationCountries() {
|
|
const items = await countryRepository.listForRegistration();
|
|
return items.map((c) => ({ code: c.code, name: c.name }));
|
|
}
|
|
async function listAllCountriesAdmin() {
|
|
const items = await countryRepository.listAll();
|
|
return items.map((c) => ({
|
|
code: c.code,
|
|
name: c.name,
|
|
registrationAllowed: c.registration_allowed,
|
|
syncedAt: c.synced_at,
|
|
updatedAt: c.updated_at,
|
|
}));
|
|
}
|
|
async function setCountryRegistrationAllowed(code, allowed) {
|
|
const row = await countryRepository.findByCode(code);
|
|
if (!row)
|
|
throw new Error('Country not found — sync the catalog first');
|
|
await countryRepository.setRegistrationAllowed(code, allowed);
|
|
}
|
|
//# sourceMappingURL=countryService.js.map
|