All files / src/clients/ep questionClient.ts

89.36% Statements 42/47
82.05% Branches 32/39
90.9% Functions 10/11
90% Lines 36/40

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                                                                      295x               91x                             21x 21x 21x 21x 1x 21x 1x   21x                     21x 21x 1x 1x 2x     21x 1x 1x 2x     21x 4x   21x       21x                                               21x 21x 21x 21x         21x 89x   21x   21x               21x 21x                               4x 2x       2x      
/**
 * @fileoverview Parliamentary Questions sub-client for European Parliament API
 *
 * Handles retrieval and filtering of parliamentary questions
 * (written, oral, interpellations, question time).
 *
 * @module clients/ep/questionClient
 */
 
import { auditLogger } from '../../utils/auditLogger.js';
import type {
  ParliamentaryQuestion,
  PaginatedResponse,
} from '../../types/europeanParliament.js';
import {
  transformParliamentaryQuestion as _transformParliamentaryQuestion,
} from './transformers.js';
import {
  BaseEPClient,
  APIError,
  type EPClientConfig,
  type EPSharedResources,
  type JSONLDResponse,
} from './baseClient.js';
 
// ─── Question Client ──────────────────────────────────────────────────────────
 
/**
 * Sub-client for parliamentary-questions EP API endpoints.
 *
 * @extends BaseEPClient
 * @public
 */
export class QuestionClient extends BaseEPClient {
  constructor(config: EPClientConfig = {}, shared?: EPSharedResources) {
    super(config, shared);
  }
 
  // ─── Transform helpers ────────────────────────────────────────────────────
 
  private transformParliamentaryQuestion(
    apiData: Record<string, unknown>
  ): ParliamentaryQuestion {
    return _transformParliamentaryQuestion(apiData);
  }
 
  // ─── Private helpers ──────────────────────────────────────────────────────
 
  /**
   * Builds EP API parameters for parliamentary question search.
   * @private
   */
  private buildQuestionSearchParams(params: {
    type?: 'WRITTEN' | 'ORAL';
    dateFrom?: string;
    limit?: number;
    offset?: number;
  }): Record<string, unknown> {
    const apiParams: Record<string, unknown> = {};
    Eif (params.limit !== undefined) apiParams['limit'] = params.limit;
    if (params.offset !== undefined) apiParams['offset'] = params.offset;
    if (params.type === 'WRITTEN') apiParams['work-type'] = 'QUESTION_WRITTEN';
    else if (params.type === 'ORAL') apiParams['work-type'] = 'QUESTION_ORAL';
    if (params.dateFrom !== undefined && params.dateFrom !== '') {
      apiParams['year'] = params.dateFrom.substring(0, 4);
    }
    return apiParams;
  }
 
  /**
   * Applies client-side filters to parliamentary questions.
   * @private
   */
  private filterQuestions(
    questions: ParliamentaryQuestion[],
    params: { author?: string; topic?: string; status?: 'PENDING' | 'ANSWERED'; dateTo?: string }
  ): ParliamentaryQuestion[] {
    let filtered = questions;
    if (params.author !== undefined && params.author !== '') {
      const authorLower = params.author.toLowerCase();
      filtered = filtered.filter((q) =>
        q.author.toLowerCase().includes(authorLower)
      );
    }
    if (params.topic !== undefined && params.topic !== '') {
      const topicLower = params.topic.toLowerCase();
      filtered = filtered.filter((q) =>
        q.topic.toLowerCase().includes(topicLower)
      );
    }
    if (params.status !== undefined) {
      filtered = filtered.filter((q) => q.status === params.status);
    }
    Iif (params.dateTo !== undefined && params.dateTo !== '') {
      const dateTo = params.dateTo;
      filtered = filtered.filter((q) => q.date <= dateTo);
    }
    return filtered;
  }
 
  // ─── Public methods ───────────────────────────────────────────────────────
 
  /**
   * Retrieves parliamentary questions with filtering by type, author, and status.
   *
   * **EP API Endpoint:** `GET /parliamentary-questions`
   *
   * @param params - type, author, topic, status, dateFrom, dateTo, limit, offset
   * @returns Paginated parliamentary questions list
   * @security Audit logged per GDPR Article 30
   */
  async getParliamentaryQuestions(params: {
    type?: 'WRITTEN' | 'ORAL';
    author?: string;
    topic?: string;
    status?: 'PENDING' | 'ANSWERED';
    dateFrom?: string;
    dateTo?: string;
    limit?: number;
    offset?: number;
  }): Promise<PaginatedResponse<ParliamentaryQuestion>> {
    const action = 'get_parliamentary_questions';
    try {
      const apiParams = this.buildQuestionSearchParams(params);
      const response = await this.get<JSONLDResponse>(
        'parliamentary-questions',
        apiParams
      );
 
      let questions = response.data.map((item) =>
        this.transformParliamentaryQuestion(item)
      );
      questions = this.filterQuestions(questions, params);
 
      const result: PaginatedResponse<ParliamentaryQuestion> = {
        data: questions,
        total: (params.offset ?? 0) + questions.length,
        limit: params.limit ?? 50,
        offset: params.offset ?? 0,
        hasMore: questions.length >= (params.limit ?? 50),
      };
 
      auditLogger.logDataAccess(action, params, result.data.length);
      return result;
    } catch (error) {
      auditLogger.logError(
        action,
        params,
        error instanceof Error ? error.message : 'Unknown error'
      );
      throw error;
    }
  }
 
  /**
   * Returns a single parliamentary question by document ID.
   * **EP API Endpoint:** `GET /parliamentary-questions/{doc-id}`
   */
  async getParliamentaryQuestionById(docId: string): Promise<ParliamentaryQuestion> {
    if (docId.trim() === '') throw new APIError('Document ID is required', 400);
    const response = await this.get<Record<string, unknown>>(
      `parliamentary-questions/${docId}`,
      { format: 'application/ld+json' }
    );
    return this.transformParliamentaryQuestion(response);
  }
}