import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; import type { z } from 'zod'; import type { ListSchema } from '../../types'; import type { AsyncListResult } from '../../utilities'; import { errorResult, successListResult, UnsupportedError, } from '../../utilities'; import type { ResourceQuery } from '../BaseResourceRepository'; import { BaseResourceRepository } from '../BaseResourceRepository'; export class BaseCustomersResourceRepository< ListResponseType extends z.infer > extends BaseResourceRepository { protected readonly _schemas: { listForCustomer?: z.ZodType; }; constructor( axios: AxiosInstance, baseUrl: string, schemas: { listForCustomer?: z.ZodType; } ) { super(axios, baseUrl); this._schemas = schemas; } public async listForCustomer( customerId: string, query?: ResourceQuery ): AsyncListResult { return this.getListPage(query, `/customers/${customerId}${this._baseUrl}`); } protected getRequestConfig( query?: ResourceQuery ): AxiosRequestConfig | undefined { const config = super.getRequestConfig(query); if (!config) return config; // TODO: Workaround to make pagination more consistent if (config.params?.['page[limit]']) { config.params.size = config.params['page[limit]']; delete config.params['page[limit]']; } if (config.params?.['page[page]']) { config.params.page = config.params['page[page]']; delete config.params['page[page]']; } return config; } public async getListPage( query: ResourceQuery = {}, url: string = this._baseUrl ): AsyncListResult { if (!this._schemas.listForCustomer) throw new UnsupportedError(); let request: AxiosResponse; let data: ListResponseType; try { request = await this._axios.get(url, this.getRequestConfig(query)); data = this._schemas.listForCustomer.parse(request.data); } catch (error) { return errorResult(error as Error); } const hasPreviousPage = !!data._links.previous?.href; const hasNextPage = !!data._links.next?.href; const previousFn = () => this.getListPage({}, data._links.previous?.href); const nextFn = () => this.getListPage({}, data._links.next?.href); const previous = hasPreviousPage ? previousFn : undefined; const next = hasNextPage ? nextFn : undefined; return successListResult( { ...data, // Make sure the pagination parameters on the URLs are consistent when they are made public on the response _links: { self: { href: formatUrl(data._links.self.href) }, previous: hasPreviousPage ? { href: formatUrl(data._links.previous?.href) } : undefined, next: hasNextPage ? { href: formatUrl(data._links.next?.href) } : undefined, }, }, previous, next ); } } /** Replace `size` with `page[limit]` and `page` with `page[page]` to be consistent with all other pagination urls */ const formatUrl = (url?: string) => { return url?.replace('size=', 'page[limit]=').replace('page=', 'page[page]='); };