All files / utils validate-ep-api.ts

96.96% Statements 32/33
84% Branches 21/25
80% Functions 4/5
100% Lines 30/30

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                                    1x     1x     1x                                                                                                                   15x 15x 15x 15x 15x   15x 15x         15x   14x   14x 2x                       12x 12x 12x 1x                       11x 11x 15x 15x   15x 15x 15x   15x                     1x                                           8x 8x 3x                                                                                                                      
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Utils/ValidateEPAPI
 * @description Validates that the European Parliament v2 API returns real data
 * for committee endpoints.  Can be run standalone as a pre-flight check or
 * imported as a library for integration tests.
 *
 * Usage:
 *   npx tsx src/utils/validate-ep-api.ts
 *   npx tsx src/utils/validate-ep-api.ts --committees=ENVI,ECON
 */
 
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
 
/** Base URL for the EP Open Data Portal v2 API */
const EP_API_V2_BASE = 'https://data.europarl.europa.eu/api/v2';
 
/** Default timeout for API requests (ms) */
const REQUEST_TIMEOUT_MS = 20_000;
 
/** Default committees to validate */
const DEFAULT_COMMITTEES = ['ENVI', 'ECON', 'AFET', 'LIBE', 'AGRI'] as const;
 
/** Shape of a corporate body item from the EP v2 API */
interface EPCorporateBodyItem {
  id?: string;
  label?: string;
  prefLabel?: Record<string, string>;
  altLabel?: Record<string, string>;
  classification?: string;
}
 
/** Result of validating a single committee endpoint */
export interface CommitteeValidationResult {
  /** Committee abbreviation code (e.g. `"ENVI"`) */
  abbreviation: string;
  /** Whether the endpoint returned usable real data */
  success: boolean;
  /** Whether a human-readable name was found */
  hasName: boolean;
  /** Whether a label/abbreviation code was found */
  hasLabel: boolean;
  /** Whether the classification identifies a standing committee */
  hasClassification: boolean;
  /** English name of the committee, or null when unavailable */
  name: string | null;
  /** Error message when the request failed, or null on success */
  error: string | null;
  /** Round-trip time in milliseconds */
  responseTimeMs: number;
}
 
/** Overall validation summary for a batch of committee checks */
export interface EPAPIValidationSummary {
  /** ISO 8601 timestamp when validation was performed */
  timestamp: string;
  /** Base URL of the EP API that was validated */
  apiBase: string;
  /** Number of committees checked */
  totalChecked: number;
  /** Number of committees that returned valid data */
  totalPassed: number;
  /** Number of committees that failed validation */
  totalFailed: number;
  /** Per-committee validation results */
  results: CommitteeValidationResult[];
  /** Whether all checked committees passed validation */
  allValid: boolean;
}
 
/**
 * Validate a single committee endpoint on the EP v2 API.
 *
 * @param abbreviation - Committee code (e.g. `"ENVI"`)
 * @returns Validation result
 */
export async function validateCommitteeEndpoint(
  abbreviation: string
): Promise<CommitteeValidationResult> {
  const url = `${EP_API_V2_BASE}/corporate-bodies/${encodeURIComponent(abbreviation)}?format=application%2Fld%2Bjson`;
  const start = Date.now();
  try {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
    let response: Response;
    try {
      response = await fetch(url, {
        signal: controller.signal,
        headers: { Accept: 'application/ld+json' },
      });
    } finally {
      clearTimeout(timer);
    }
    const responseTimeMs = Date.now() - start;
 
    if (!response.ok) {
      return {
        abbreviation,
        success: false,
        hasName: false,
        hasLabel: false,
        hasClassification: false,
        name: null,
        error: `HTTP ${String(response.status)}`,
        responseTimeMs,
      };
    }
 
    const body = (await response.json()) as { data?: EPCorporateBodyItem[] };
    const items = body.data;
    if (!Array.isArray(items) || items.length === 0) {
      return {
        abbreviation,
        success: false,
        hasName: false,
        hasLabel: false,
        hasClassification: false,
        name: null,
        error: 'No data items in response',
        responseTimeMs,
      };
    }
 
    const item = items[0];
    const name = item?.prefLabel?.['en'] ?? item?.altLabel?.['en'] ?? null;
    const label = item?.label ?? null;
    const classification = item?.classification ?? null;
 
    const hasName = name !== null && name.length > 0;
    const hasLabel = label !== null && label.length > 0;
    const hasClassification = classification?.includes('COMMITTEE') ?? false;
 
    return {
      abbreviation,
      success: hasName && hasLabel && hasClassification,
      hasName,
      hasLabel,
      hasClassification,
      name,
      error: null,
      responseTimeMs,
    };
  } catch (err) {
    return {
      abbreviation,
      success: false,
      hasName: false,
      hasLabel: false,
      hasClassification: false,
      name: null,
      error: err instanceof Error ? err.message : String(err),
      responseTimeMs: Date.now() - start,
    };
  }
}
 
/**
 * Validate all specified committee endpoints and return a summary.
 *
 * @param committees - Array of committee abbreviations to validate
 * @returns Validation summary
 */
export async function validateEPAPI(
  committees: readonly string[] = DEFAULT_COMMITTEES
): Promise<EPAPIValidationSummary> {
  const results = await Promise.all(committees.map((abbr) => validateCommitteeEndpoint(abbr)));
  const totalPassed = results.filter((r) => r.success).length;
  return {
    timestamp: new Date().toISOString(),
    apiBase: EP_API_V2_BASE,
    totalChecked: results.length,
    totalPassed,
    totalFailed: results.length - totalPassed,
    results,
    allValid: totalPassed === results.length,
  };
}
 
// ─── CLI entry point ────────────────────────────────────────────────────────
 
/* c8 ignore start */
async function main(): Promise<void> {
  const args = process.argv.slice(2);
  const committeesArg = args.find((a) => a.startsWith('--committees='));
  const parsedCommittees = committeesArg
    ? committeesArg
        .replace('--committees=', '')
        .split(',')
        .map((committee) => committee.trim())
        .filter((committee) => committee.length > 0)
    : [];
  const committees = parsedCommittees.length > 0 ? parsedCommittees : [...DEFAULT_COMMITTEES];
 
  console.log(`\n🔍 Validating EP v2 API for committees: ${committees.join(', ')}\n`);
 
  const summary = await validateEPAPI(committees);
 
  for (const r of summary.results) {
    const icon = r.success ? '✅' : '❌';
    const detail = r.success
      ? `${r.name} (${String(r.responseTimeMs)}ms)`
      : `Error: ${r.error ?? 'unknown'} (${String(r.responseTimeMs)}ms)`;
    console.log(`  ${icon} ${r.abbreviation}: ${detail}`);
  }
 
  console.log(
    `\n📊 Summary: ${String(summary.totalPassed)}/${String(summary.totalChecked)} passed`
  );
 
  if (!summary.allValid) {
    console.error('\n❌ EP v2 API validation failed — some endpoints returned no real data');
    process.exitCode = 1;
  } else {
    console.log('\n✅ All EP v2 API committee endpoints returned real data');
  }
}
 
// Only run if executed directly (not imported)
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  main().catch((err: unknown) => {
    const message = err instanceof Error ? err.message : String(err);
    console.error('Fatal error:', message);
    process.exitCode = 1;
  });
}
/* c8 ignore stop */