Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 | 27x 27x 27x 27x 27x 27x 27x 43x 43x 43x 161x 161x 161x 158x 146x 12x 12x 11x 4x 4x 4x 4x 4x 4x 6x 5x 2x 2x 4x 4x 3x 1x 2x 162x 162x 162x 162x 159x 1x 158x 4x 1x 1x 1x 3x 162x 27x 3x 1x 3x | /**
* @module WorldBank/Client
* @description TypeScript REST client for the World Bank Open Data API.
* Provides direct HTTP access to World Bank economic indicators for Sweden
* and Nordic comparison countries, used to enrich political intelligence
* with economic context.
*
* Based on the World Bank MCP Server pattern (https://github.com/anshumax/world_bank_mcp_server)
* but implemented as a native TypeScript HTTP client for build-time data fetching.
*
* @author Hack23 AB
* @license Apache-2.0
* @see https://datahelpdesk.worldbank.org/knowledgebase/articles/889392-about-the-indicators-api-documentation
*/
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** A single World Bank indicator data point */
export interface WorldBankDataPoint {
readonly countryId: string;
readonly countryName: string;
readonly indicatorId: string;
readonly indicatorName: string;
readonly date: string;
readonly value: number;
}
/** Metadata about a World Bank indicator */
export interface WorldBankIndicator {
readonly id: string;
readonly name: string;
readonly description: string;
readonly unit: string;
}
/** Raw indicator value from the API */
interface RawIndicatorValue {
indicator?: { id?: string; value?: string };
country?: { id?: string; value?: string };
date?: string;
value?: number | null;
}
/** Client configuration */
export interface WorldBankClientConfig {
readonly baseURL?: string;
readonly timeout?: number;
readonly maxRetries?: number;
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const DEFAULT_BASE_URL = 'https://api.worldbank.org/v2';
const DEFAULT_TIMEOUT = 15_000;
const DEFAULT_MAX_RETRIES = 2;
/**
* World Bank API source IDs for different indicator databases.
* Most indicators use the default WDI source (2), but Worldwide
* Governance Indicators (WGI) require source=75.
*/
export const WB_SOURCES = {
/** World Development Indicators (default) */
wdi: 2,
/** Worldwide Governance Indicators — needed for CC.EST, RQ.EST, PV.EST, GE.EST, RL.EST, VA.EST */
wgi: 75,
} as const;
/** Indicator IDs that require source=75 (WGI) for REST API access */
export const WGI_INDICATOR_IDS = new Set([
'RL.EST', 'VA.EST', 'GE.EST', 'RQ.EST', 'CC.EST', 'PV.EST',
]);
/** ISO 3166-1 alpha-3 codes for Sweden and comparison countries */
export const COUNTRY_CODES = {
sweden: 'SWE',
denmark: 'DNK',
norway: 'NOR',
finland: 'FIN',
germany: 'DEU',
eu: 'EUU',
} as const;
/**
* Comprehensive World Bank indicator IDs for Swedish political intelligence.
*
* Organised into 17 domains covering all Riksdag committee policy areas.
* Total: 144 verified indicators with Sweden annual time-series data.
*
* Access methods:
* - **MCP tools**: get-economic-data, get-social-data, get-education-data, get-health-data
* - **REST API**: api.worldbank.org/v2 (default source=2/WDI)
* - **WGI REST API**: api.worldbank.org/v2 with source=75 (governance indicators)
*
* Full machine-readable inventory: analysis/worldbank/indicators-inventory.json
* Committee mapping: analysis/worldbank/indicator-policy-mapping.md
*/
export const INDICATOR_IDS = {
// ===========================================================================
// 1. NATIONAL ACCOUNTS & GDP (FiU — Finance Committee)
// ===========================================================================
/** GDP (current US$) */
gdp: 'NY.GDP.MKTP.CD',
/** GDP growth (annual %) */
gdpGrowth: 'NY.GDP.MKTP.KD.ZG',
/** GDP (constant LCU) */
gdpConstantLcu: 'NY.GDP.MKTP.KN',
/** GDP, PPP (current international $) */
gdpPpp: 'NY.GDP.MKTP.PP.CD',
/** GDP per capita (current US$) */
gdpPerCapita: 'NY.GDP.PCAP.CD',
/** GDP per capita growth (annual %) */
gdpPerCapitaGrowth: 'NY.GDP.PCAP.KD.ZG',
/** GDP per capita, PPP (current international $) */
gdpPerCapitaPpp: 'NY.GDP.PCAP.PP.CD',
/** GDP per capita, PPP (constant 2021 international $) */
gdpPerCapitaPppConst: 'NY.GDP.PCAP.PP.KD',
/** General government final consumption expenditure (% of GDP) */
govConsumption: 'NE.CON.GOVT.ZS',
/** Households final consumption expenditure (% of GDP) */
householdConsumption: 'NE.CON.PRVT.ZS',
/** Gross capital formation (% of GDP) */
grossCapitalFormation: 'NE.GDI.TOTL.ZS',
/** Gross fixed capital formation (% of GDP) */
grossFixedCapital: 'NE.GDI.FTOT.ZS',
/** Gross savings (% of GDP) */
grossSavings: 'NY.GNS.ICTR.ZS',
/** Adjusted net national income per capita (current US$) */
adjNetNationalIncome: 'NY.ADJ.NNTY.PC.CD',
/** GNI (current US$) */
gni: 'NY.GNP.MKTP.CD',
/** GNI per capita, Atlas method (current US$) */
gniPerCapita: 'NY.GNP.PCAP.CD',
/** GNI per capita, PPP (current international $) */
gniPerCapitaPpp: 'NY.GNP.PCAP.PP.CD',
// ===========================================================================
// 2. GOVERNMENT FINANCE & TAXATION (SkU, FiU)
// ===========================================================================
/** Tax revenue (% of GDP) */
taxRevenue: 'GC.TAX.TOTL.GD.ZS',
/** Expense (% of GDP) */
govExpenditure: 'GC.XPN.TOTL.GD.ZS',
/** Revenue, excluding grants (% of GDP) */
govRevenue: 'GC.REV.XGRT.GD.ZS',
/** Taxes on goods and services (% of revenue) */
taxGoodsServices: 'GC.TAX.GSRV.RV.ZS',
/** Taxes on income, profits and capital gains (% of revenue) */
taxIncome: 'GC.TAX.YPKG.RV.ZS',
/** Taxes on international trade (% of revenue) */
taxTrade: 'GC.TAX.INTT.RV.ZS',
/** Net investment in nonfinancial assets (% of GDP) */
netInvestment: 'GC.NFN.TOTL.GD.ZS',
/** Cash surplus/deficit (% of GDP) */
cashSurplusDeficit: 'GC.BAL.CASH.GD.ZS',
/** Net lending (+) / net borrowing (-) (% of GDP) */
netLending: 'GC.NLD.TOTL.GD.ZS',
// ===========================================================================
// 3. TRADE & BALANCE OF PAYMENTS (NU, UU)
// ===========================================================================
/** Trade (% of GDP) */
tradeGdpPct: 'NE.TRD.GNFS.ZS',
/** Exports of goods and services (% of GDP) */
exportsGdpPct: 'NE.EXP.GNFS.ZS',
/** Imports of goods and services (% of GDP) */
importsGdpPct: 'NE.IMP.GNFS.ZS',
/** Exports of goods and services (current US$) */
exportsUsd: 'NE.EXP.GNFS.CD',
/** Imports of goods and services (current US$) */
importsUsd: 'NE.IMP.GNFS.CD',
/** Current account balance (% of GDP) */
currentAccountBalance: 'BN.CAB.XOKA.GD.ZS',
/** Foreign direct investment, net inflows (BoP, current US$) */
fdiNet: 'BN.KLT.DINV.CD',
/** Foreign direct investment, net inflows (% of GDP) */
fdiNetGdpPct: 'BX.KLT.DINV.WD.GD.ZS',
/** Foreign direct investment, net outflows (% of GDP) */
fdiOutGdpPct: 'BM.KLT.DINV.WD.GD.ZS',
/** High-technology exports (% of manufactured exports) */
highTechExports: 'TX.VAL.TECH.MF.ZS',
/** External balance on goods and services (% of GDP) */
externalBalance: 'NE.RSB.GNFS.ZS',
// ===========================================================================
// 4. LABOR MARKET & EMPLOYMENT (AU — Labor Market Committee)
// ===========================================================================
/** Unemployment, total (% of total labor force) */
unemployment: 'SL.UEM.TOTL.ZS',
/** Unemployment, female (% of female labor force) */
unemploymentFemale: 'SL.UEM.TOTL.FE.ZS',
/** Unemployment, male (% of male labor force) */
unemploymentMale: 'SL.UEM.TOTL.MA.ZS',
/** Unemployment, youth total (% 15-24) */
youthUnemployment: 'SL.UEM.1524.ZS',
/** Unemployment, youth female (% 15-24) */
youthUnemploymentFemale: 'SL.UEM.1524.FE.ZS',
/** Unemployment, youth male (% 15-24) */
youthUnemploymentMale: 'SL.UEM.1524.MA.ZS',
/** Long-term unemployment (% of total unemployment) */
longTermUnemployment: 'SL.UEM.LTRM.ZS',
/** Long-term unemployment, female (%) */
longTermUnemploymentFemale: 'SL.UEM.LTRM.FE.ZS',
/** Long-term unemployment, male (%) */
longTermUnemploymentMale: 'SL.UEM.LTRM.MA.ZS',
/** Labor force participation rate, total (% ages 15+) */
laborForceParticipation: 'SL.TLF.CACT.ZS',
/** Labor force participation rate, female (% ages 15+) */
laborForceParticipationFemale: 'SL.TLF.CACT.FE.ZS',
/** Labor force participation rate, male (% ages 15+) */
laborForceParticipationMale: 'SL.TLF.CACT.MA.ZS',
/** Labor force, total */
laborForceTotal: 'SL.TLF.TOTL.IN',
/** Employment to population ratio, 15+, total (%) */
employmentRatio: 'SL.EMP.TOTL.SP.ZS',
/** Employment to population ratio, 15+, female (%) */
employmentRatioFemale: 'SL.EMP.TOTL.SP.FE.ZS',
/** Employment to population ratio, 15+, male (%) */
employmentRatioMale: 'SL.EMP.TOTL.SP.MA.ZS',
/** Vulnerable employment, total (% of total employment) */
vulnerableEmployment: 'SL.EMP.VULN.ZS',
/** Self-employed, total (% of total employment) */
selfEmployed: 'SL.EMP.SELF.ZS',
/** Wage and salaried workers, total (% of total employment) */
wageSalariedWorkers: 'SL.EMP.WORK.ZS',
/** GDP per person employed (constant 2021 PPP $) */
laborProductivity: 'SL.GDP.PCAP.EM.KD',
// ===========================================================================
// 5. INFLATION & PRICES (FiU)
// ===========================================================================
/** Inflation, consumer prices (annual %) */
inflation: 'FP.CPI.TOTL.ZG',
/** Inflation, GDP deflator (annual %) */
inflationGdpDeflator: 'NY.GDP.DEFL.KD.ZG',
/** Consumer price index (2010 = 100) */
consumerPriceIndex: 'FP.CPI.TOTL',
// ===========================================================================
// 6. FINANCIAL SECTOR (FiU)
// ===========================================================================
/** Domestic credit to private sector by banks (% of GDP) */
domesticCreditBanks: 'FS.AST.PRVT.GD.ZS',
/** Real interest rate (%) */
realInterestRate: 'FR.INR.RINR',
/** Lending interest rate (%) */
lendingRate: 'FR.INR.LEND',
/** Deposit interest rate (%) */
depositRate: 'FR.INR.DPST',
// ===========================================================================
// 7. DEMOGRAPHICS & POPULATION (SoU — Social Affairs Committee)
// ===========================================================================
/** Population, total */
population: 'SP.POP.TOTL',
/** Population growth (annual %) */
populationGrowth: 'SP.POP.GROW',
/** Population ages 65 and above (% of total) */
population65Plus: 'SP.POP.65UP.TO.ZS',
/** Population ages 0-14 (% of total) */
populationChildren: 'SP.POP.0014.TO.ZS',
/** Population ages 15-64 (% of total) */
populationWorkingAge: 'SP.POP.1564.TO.ZS',
/** Urban population (% of total) */
urbanPopulation: 'SP.URB.TOTL.IN.ZS',
/** Rural population (% of total) */
ruralPopulation: 'SP.RUR.TOTL.ZS',
/** Age dependency ratio (% of working-age population) */
ageDependencyRatio: 'SP.POP.DPND',
/** Age dependency ratio, old (% of working-age) */
ageDependencyOld: 'SP.POP.DPND.OL',
/** Age dependency ratio, young (% of working-age) */
ageDependencyYoung: 'SP.POP.DPND.YG',
/** Net migration */
netMigration: 'SM.POP.NETM',
/** Refugee population by country/territory of asylum */
refugeePopulation: 'SM.POP.REFG',
/** Life expectancy at birth, total (years) */
lifeExpectancy: 'SP.DYN.LE00.IN',
/** Life expectancy at birth, female (years) */
lifeExpectancyFemale: 'SP.DYN.LE00.FE.IN',
/** Life expectancy at birth, male (years) */
lifeExpectancyMale: 'SP.DYN.LE00.MA.IN',
/** Birth rate, crude (per 1,000 people) */
birthRate: 'SP.DYN.CBRT.IN',
/** Death rate, crude (per 1,000 people) */
deathRate: 'SP.DYN.CDRT.IN',
/** Fertility rate, total (births per woman) */
fertilityRate: 'SP.DYN.TFRT.IN',
/** Adolescent fertility rate (births per 1,000 women ages 15-19) */
adolescentFertility: 'SP.ADO.TFRT',
/** Mortality rate, infant (per 1,000 live births) */
infantMortality: 'SP.DYN.IMRT.IN',
/** Mortality rate, under-5 (per 1,000 live births) */
under5Mortality: 'SH.DYN.MORT',
// ===========================================================================
// 8. HEALTH (SoU)
// ===========================================================================
/** Current health expenditure (% of GDP) */
healthExpenditure: 'SH.XPD.CHEX.GD.ZS',
/** Current health expenditure per capita (current US$) */
healthExpenditurePerCapita: 'SH.XPD.CHEX.PC.CD',
/** Domestic general government health expenditure (% of GDP) */
govHealthExpenditure: 'SH.XPD.GHED.GD.ZS',
/** Domestic general government health exp. (% of current health exp.) */
govHealthShare: 'SH.XPD.GHED.CH.ZS',
/** Domestic private health expenditure (% of current health exp.) */
privateHealthShare: 'SH.XPD.PVTD.CH.ZS',
/** Out-of-pocket expenditure (% of current health expenditure) */
outOfPocketHealth: 'SH.XPD.OOPC.CH.ZS',
/** Physicians (per 1,000 people) */
physicians: 'SH.MED.PHYS.ZS',
/** Hospital beds (per 1,000 people) */
hospitalBeds: 'SH.MED.BEDS.ZS',
/** Nurses and midwives (per 1,000 people) */
nursesAndMidwives: 'SH.MED.NUMW.P3',
/** Suicide mortality rate (per 100,000 population) */
suicideMortality: 'SH.STA.SUIC.P5',
/** Prevalence of current tobacco use (% of adults) */
tobaccoUse: 'SH.PRV.SMOK',
/** Total alcohol consumption per capita (liters of pure alcohol) */
alcoholConsumption: 'SH.ALC.PCAP.LI',
/** Immunization, measles (% of children ages 12-23 months) */
measlesImmunization: 'SH.IMM.MEAS',
/** Immunization, DPT (% of children ages 12-23 months) */
dptImmunization: 'SH.IMM.IDPT',
// ===========================================================================
// 9. EDUCATION (UbU — Education Committee)
// ===========================================================================
/** Government expenditure on education, total (% of GDP) */
educationExpenditure: 'SE.XPD.TOTL.GD.ZS',
/** Government expenditure on education (% of government expenditure) */
educationGovShare: 'SE.XPD.TOTL.GB.ZS',
/** School enrollment, primary (% gross) */
schoolEnrollment: 'SE.PRM.ENRR',
/** School enrollment, secondary (% gross) */
secondaryEnrollment: 'SE.SEC.ENRR',
/** School enrollment, tertiary (% gross) */
tertiaryEnrollment: 'SE.TER.ENRR',
/** Primary completion rate (% of relevant age group) */
primaryCompletion: 'SE.PRM.CMPT.ZS',
// ===========================================================================
// 10. ENVIRONMENT & CLIMATE (MJU — Environment Committee)
// ===========================================================================
/** CO2 emissions (metric tons per capita) */
co2Emissions: 'EN.ATM.CO2E.PC',
/** CO2 emissions (kt) */
co2EmissionsTotal: 'EN.ATM.CO2E.KT',
/** Energy use (kg of oil equivalent per capita) */
energyUse: 'EG.USE.PCAP.KG.OE',
/** Renewable energy consumption (% of total final energy) */
renewableEnergy: 'EG.FEC.RNEW.ZS',
/** Renewable electricity output (% of total electricity output) */
renewableElectricity: 'EG.ELC.RNEW.ZS',
/** Forest area (% of land area) */
forestArea: 'AG.LND.FRST.ZS',
/** PM2.5 air pollution, mean annual exposure (µg/m³) */
airPollution: 'EN.ATM.PM25.MC.M3',
/** Electricity production from nuclear sources (% of total) */
nuclearElectricity: 'EG.ELC.NUCL.ZS',
/** Electricity production from hydroelectric sources (% of total) */
hydroElectricity: 'EG.ELC.HYRO.ZS',
/** Electricity production from renewables excl. hydro (% of total) */
renewableElecExHydro: 'EG.ELC.RNWX.ZS',
// ===========================================================================
// 11. INFRASTRUCTURE & TECHNOLOGY (TU — Transport Committee)
// ===========================================================================
/** Individuals using the Internet (% of population) */
internetUsers: 'IT.NET.USER.ZS',
/** Fixed broadband subscriptions (per 100 people) */
broadbandSubscriptions: 'IT.NET.BBND.P2',
/** Mobile cellular subscriptions (per 100 people) */
mobileSubscriptions: 'IT.CEL.SETS.P2',
/** Secure Internet servers (per 1 million people) */
secureServers: 'IT.NET.SECR.P6',
/** Air transport, passengers carried */
airPassengers: 'IS.AIR.PSGR',
/** Patent applications, residents */
patentsResident: 'IP.PAT.RESD',
/** Patent applications, nonresidents */
patentsNonresident: 'IP.PAT.NRES',
// ===========================================================================
// 12. INNOVATION & RESEARCH (UbU)
// ===========================================================================
/** Research and development expenditure (% of GDP) */
rdExpenditure: 'GB.XPD.RSDV.GD.ZS',
/** Researchers in R&D (per million people) */
researchersPerMillion: 'SP.POP.SCIE.RD.P6',
/** Scientific and technical journal articles */
scientificArticles: 'IP.JRN.ARTC.SC',
/** ICT service exports (% of service exports, BoP) */
ictServiceExports: 'BX.GSR.CCIS.ZS',
// ===========================================================================
// 13. MILITARY & SECURITY (FöU — Defense Committee)
// ===========================================================================
/** Military expenditure (% of GDP) */
militaryExpenditure: 'MS.MIL.XPND.GD.ZS',
/** Military expenditure (current USD) */
militaryExpenditureUsd: 'MS.MIL.XPND.CD',
/** Military expenditure (% of central government expenditure) */
militaryGovShare: 'MS.MIL.XPND.ZS',
/** Armed forces personnel, total */
armedForcesTotal: 'MS.MIL.TOTL.P1',
/** Armed forces personnel (% of total labor force) */
armedForcesLaborShare: 'MS.MIL.TOTL.TF.ZS',
// ===========================================================================
// 14. GOVERNANCE & INSTITUTIONS (KU, JuU)
// Note: WGI indicators require source=75 in REST API calls
// ===========================================================================
/** Rule of Law: Estimate (-2.5 to 2.5) [source=75] */
ruleOfLaw: 'RL.EST',
/** Voice and Accountability: Estimate [source=75] */
voiceAccountability: 'VA.EST',
/** Government Effectiveness: Estimate [source=75] */
govEffectiveness: 'GE.EST',
/** Regulatory Quality: Estimate [source=75] */
regulatoryQuality: 'RQ.EST',
/** Control of Corruption: Estimate [source=75] */
controlOfCorruption: 'CC.EST',
/** Political Stability and Absence of Violence: Estimate [source=75] */
politicalStability: 'PV.EST',
// ===========================================================================
// 15. INEQUALITY & POVERTY (SoU, AU)
// ===========================================================================
/** GINI index */
giniIndex: 'SI.POV.GINI',
/** Income share held by highest 10% */
incomeTop10: 'SI.DST.10TH.10',
/** Income share held by lowest 10% */
incomeBottom10: 'SI.DST.FRST.10',
/** Income share held by lowest 20% */
incomeBottom20: 'SI.DST.FRST.20',
/** Income share held by highest 20% */
incomeTop20: 'SI.DST.05TH.20',
// ===========================================================================
// 16. GENDER & SOCIAL INCLUSION (AU, KU)
// ===========================================================================
/** Proportion of seats held by women in national parliaments (%) */
womenInParliament: 'SG.GEN.PARL.ZS',
// ===========================================================================
// 17. ENERGY (MJU, NU)
// ===========================================================================
/** Electric power consumption (kWh per capita) */
electricPowerConsumption: 'EG.USE.ELEC.KH.PC',
} as const;
// ---------------------------------------------------------------------------
// WorldBankClient class
// ---------------------------------------------------------------------------
/**
* HTTP client for the World Bank Open Data API.
* Fetches economic indicator data for Sweden and comparison countries.
*/
export class WorldBankClient {
readonly baseURL: string;
readonly timeout: number;
readonly maxRetries: number;
constructor(config: WorldBankClientConfig = {}) {
this.baseURL = config.baseURL ?? DEFAULT_BASE_URL;
this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
}
/**
* Fetch indicator data for a specific country.
*
* @param countryCode - ISO 3166-1 alpha-3 country code (e.g., 'SWE')
* @param indicatorId - World Bank indicator ID (e.g., 'NY.GDP.MKTP.KD.ZG')
* @param perPage - Maximum number of records to fetch (default: 50)
* @returns Array of data points sorted by date descending
*/
async getIndicator(
countryCode: string,
indicatorId: string,
perPage = 50,
): Promise<WorldBankDataPoint[]> {
// WGI governance indicators require source=75
const sourceParam = WGI_INDICATOR_IDS.has(indicatorId) ? `&source=${WB_SOURCES.wgi}` : '';
const url = `${this.baseURL}/country/${encodeURIComponent(countryCode)}/indicator/${encodeURIComponent(indicatorId)}?format=json&per_page=${perPage}${sourceParam}`;
const data = await this.fetchWithRetry(url);
if (!Array.isArray(data) || data.length < 2 || !Array.isArray(data[1])) {
return [];
}
return (data[1] as RawIndicatorValue[])
.filter((item): item is RawIndicatorValue & { value: number } => item.value !== null && item.value !== undefined)
.map((item) => ({
countryId: item.country?.id ?? countryCode,
countryName: item.country?.value ?? countryCode,
indicatorId: item.indicator?.id ?? indicatorId,
indicatorName: item.indicator?.value ?? indicatorId,
date: item.date ?? '',
value: item.value,
}))
.sort((a, b) => {
const yearA = parseInt(a.date, 10);
const yearB = parseInt(b.date, 10);
Iif (isNaN(yearA) && isNaN(yearB)) return 0;
Iif (isNaN(yearA)) return 1;
Iif (isNaN(yearB)) return -1;
return yearB - yearA;
});
}
/**
* Fetch the latest available value for an indicator.
*
* @param countryCode - ISO 3166-1 alpha-3 country code
* @param indicatorId - World Bank indicator ID
* @returns Most recent data point, or null if no data
*/
async getLatestIndicator(
countryCode: string,
indicatorId: string,
): Promise<WorldBankDataPoint | null> {
const results = await this.getIndicator(countryCode, indicatorId, 10);
return results.length > 0 ? results[0] : null;
}
/**
* Compare an indicator across multiple countries.
*
* @param countryCodes - Array of ISO 3166-1 alpha-3 codes
* @param indicatorId - World Bank indicator ID
* @returns Map of country code → latest data point
*/
async compareCountries(
countryCodes: readonly string[],
indicatorId: string,
): Promise<Map<string, WorldBankDataPoint | null>> {
const results = new Map<string, WorldBankDataPoint | null>();
// Fetch sequentially to respect API rate limits
for (const code of countryCodes) {
try {
const latest = await this.getLatestIndicator(code, indicatorId);
results.set(code, latest);
} catch {
results.set(code, null);
}
}
return results;
}
// -----------------------------------------------------------------------
// Internal helpers
// -----------------------------------------------------------------------
private async fetchWithRetry(url: string, attempt = 0): Promise<unknown> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
try {
const response = await fetch(url, {
signal: controller.signal,
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error(`World Bank API error: ${response.status} ${response.statusText}`);
}
return await response.json();
} catch (error) {
if (attempt < this.maxRetries) {
const delay = 1000 * (attempt + 1);
await new Promise((resolve) => setTimeout(resolve, delay));
return this.fetchWithRetry(url, attempt + 1);
}
throw error;
} finally {
clearTimeout(timeoutId);
}
}
}
// ---------------------------------------------------------------------------
// Singleton
// ---------------------------------------------------------------------------
let defaultWorldBankClient: WorldBankClient | null = null;
/** Get or create the default singleton WorldBankClient */
export function getDefaultWorldBankClient(): WorldBankClient {
if (!defaultWorldBankClient) {
defaultWorldBankClient = new WorldBankClient();
}
return defaultWorldBankClient;
}
|