All files / scripts/parliamentary-data/persistence scb.ts

100% Statements 8/8
100% Branches 3/3
100% Functions 1/1
100% Lines 8/8

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                                                          7x 7x   7x 7x 7x           7x 7x                     7x    
/**
 * @module parliamentary-data/persistence/scb
 * @description Statistics Sweden (SCB) PxWeb table persistence.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import fs from 'node:fs';
import path from 'node:path';
 
import { sanitizeDokId } from './shared/sanitize.js';
import { DATA_ROOT, ensureDir } from './shared/meta-sidecar.js';
 
/**
 * Persist SCB (Statistics Sweden) table data.
 * Stored under `analysis/data/scb/{tableId}.json`
 *
 * @param tableId   - SCB table identifier (e.g. 'BE0101A')
 * @param response  - Raw SCB API response data
 * @param query     - Optional query parameters used for provenance
 * @param dataRoot  - Override for the data root directory (for testing)
 */
export function persistSCBData(
  tableId: string,
  response: unknown,
  query?: Record<string, unknown>,
  dataRoot: string = DATA_ROOT,
): string {
  const dir = path.join(dataRoot, 'scb');
  ensureDir(dir);
 
  const sanitized = sanitizeDokId(tableId);
  const filename = `${sanitized}.json`;
  fs.writeFileSync(
    path.join(dir, filename),
    JSON.stringify(response, null, 2),
    'utf8',
  );
 
  const metaFilename = `${sanitized}.meta.json`;
  fs.writeFileSync(
    path.join(dir, metaFilename),
    JSON.stringify({
      fetchedAt: new Date().toISOString(),
      mcpTool: 'scb-pxweb',
      tableId,
      ...(query ? { query } : {}),
    }, null, 2),
    'utf8',
  );
 
  return path.join(dir, filename);
}