@@ -3,6 +3,63 @@ import type { TasksForImport } from '$lib/types/task';
33import { delay } from '$lib/utils/time' ;
44
55/**
6+ * A client for making HTTP requests to an API with a base URL.
7+ *
8+ * @class HttpRequestClient
9+ * @classdesc Provides functionality to make API calls with configurable endpoints and validation.
10+ */
11+ export class HttpRequestClient {
12+ /**
13+ * Creates an instance of HttpRequestClient.
14+ *
15+ * @param {string } baseApiUrl - The base URL for all API requests.
16+ */
17+ constructor ( private baseApiUrl : string ) { }
18+
19+ /**
20+ * Fetches data from an API endpoint with the provided configuration.
21+ *
22+ * @template T - The expected type of data to be returned from the API.
23+ * @param {FetchAPIConfig<T> } config - The configuration for the API request.
24+ * @param {string } config.endpoint - The API endpoint to fetch from, which will be appended to the base URL.
25+ * @param {string } config.errorMessage - The error message to use if the request fails.
26+ * @param {function(T): boolean } [config.validateResponse] - Optional function to validate the response data.
27+ *
28+ * @returns {Promise<T> } A promise that resolves to the data fetched from the API.
29+ *
30+ * @throws {Error } If the request fails, validation fails, or any other error occurs during the request.
31+ */
32+ async fetchApiWithConfig < T > ( config : FetchAPIConfig < T > ) : Promise < T > {
33+ const { endpoint, errorMessage, validateResponse } = config ;
34+
35+ try {
36+ const url = new URL ( endpoint , this . baseApiUrl ) . toString ( ) ;
37+ const data = await fetchAPI < T > ( url , config . errorMessage ) ;
38+
39+ if ( validateResponse && ! validateResponse ( data ) ) {
40+ throw new Error ( `${ errorMessage } . Response validation failed for ${ url } ` ) ;
41+ }
42+
43+ return data ;
44+ } catch ( error ) {
45+ throw new Error ( `Failed to fetch from ${ endpoint } : ${ error } ` ) ;
46+ }
47+ }
48+ }
49+
50+ /**
51+ * Client interface for interacting with tasks and contests API endpoints.
52+ *
53+ * @template T - The type of parameters to pass to API methods, defaults to void if not specified.
54+ */
55+ export interface TasksApiClient < T = void > {
56+ getContests ( params ?: T ) : Promise < ContestsForImport > ;
57+ getTasks ( params ?: T ) : Promise < TasksForImport > ;
58+ }
59+
60+ /**
61+ * @deprecated Use `HttpRequestClient` instead.
62+ *
663 * An abstract class representing a client for contest sites' APIs.
764 * This class provides methods to fetch contests and tasks, and a protected method to fetch data from an API endpoint with a given configuration.
865 *
0 commit comments