import {z} from 'zod' export type GetApiStatesArgs = {countryId?: number | undefined, isActive?: boolean | undefined, search?: string | undefined, page: number, size: number}; export type GetApiStatesOptions = {baseUrl?: string | undefined, accessToken?: string | undefined, fetch?: typeof fetch | undefined}; export const countryResponseDto = z.object({id: z.number(), countryName: z.string(), currencyCode: z.string(), currencySymbol: z.string(), mailFrom: z.string(), supportMail: z.string(), isActive: z.boolean(), isDeleted: z.boolean(), emailSignature: z.string().nullable(), displayName: z.string().nullable()}); export const stateResponseDto = z.object({id: z.number(), countryId: z.number(), stateName: z.string(), externalLink: z.string().nullable(), isActive: z.boolean(), isDeleted: z.boolean(), country: countryResponseDto}); export const getApiStatesResponse = z.array(stateResponseDto); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Get states with filters * * GET /states */ export const getApiStates = async (args: GetApiStatesArgs, options?: GetApiStatesOptions) => { const {baseUrl = "https://api.findmydocument.net", fetch: fetchFn = fetch, accessToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.countryId != null) query.append("countryId", String(args.countryId)) if (args.isActive != null) query.append("isActive", String(args.isActive)) if (args.search != null) query.append("search", String(args.search)) if (args.page != null) query.append("page", String(args.page)) if (args.size != null) query.append("size", String(args.size)) if (accessToken !== undefined) headers.set('authorization', `Bearer ${accessToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/states${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiStatesResponse, await res.json()) };