import type { AxiosInstance, 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 BaseUsersResourceRepository< GetResponseType, ListResponseType extends z.infer > extends BaseResourceRepository { protected readonly _schemas: { get?: z.ZodType; listForUser?: z.ZodType; }; constructor( axios: AxiosInstance, baseUrl: string, schemas: { get?: z.ZodType; listForUser?: z.ZodType; } ) { super(axios, baseUrl); this._schemas = schemas; } public async listForUser( userId: string, query?: ResourceQuery ): AsyncListResult { return this.getListPage(query, `/users/${userId}${this._baseUrl}`); } async getListPage( query: ResourceQuery = {}, url: string = this._baseUrl ): AsyncListResult { if (!this._schemas.listForUser) throw new UnsupportedError(); let request: AxiosResponse; let data: ListResponseType; try { request = await this._axios.get(url, this.getRequestConfig(query)); data = this._schemas.listForUser.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, previous, next); } }