import {isOfType} from '@myparcel/ts-utils'; import { type AbstractEndpoint, ApiException, type EndpointResponse, type EndpointResponseBody, type EndpointResponseProperty, type ErrorResponse, FetchClient, type Options, type ResponseWrapper, } from '@myparcel/sdk'; import {type PdkNotification} from '../types'; import {useNotificationStore} from '../stores'; type EndpointResponseBodyWithNotifications = { notifications: PdkNotification[]; }; type PdkEndpointResponseBody = EndpointResponseBody & EndpointResponseBodyWithNotifications; export class PdkFetchClient extends FetchClient { /** * Prepare and execute the final request and handle the response. */ public async doRequest(endpoint: E, options: Options): Promise> { const newOptions = this.normalizeOptions(endpoint, {...options, ...this.options}); this.validateHeaders(endpoint, newOptions); const response = (await this.request(endpoint, newOptions)) as ResponseWrapper>; if (isOfType(response, 'errors')) { if (isOfType(response, 'notifications')) { const notificationStore = useNotificationStore(); response.notifications.forEach((notification) => { notificationStore.add(notification); }); } throw new ApiException(response); } if (isOfType(response, 'data')) { const property = endpoint.getResponseProperty() as EndpointResponseProperty; if (isOfType(response.data, 'notifications')) { const notificationStore = useNotificationStore(); response.data.notifications.forEach((notification) => { notificationStore.add(notification); }); } return response.data[property]; } return response; } /** * If the url already contains a query string, append the parameters with an ampersand instead. */ protected createUrl(endpoint: E, options: Options): string { const url = super.createUrl(endpoint, options); return url.replace(/\?([^?]*)(\?)/, '?$1&'); } }