import {z} from 'zod' export type GetApiFreeSlotsArgs = {serviceId: number, locationId: number, practitionerIds: Array, from: string | string, to?: (string | string) | undefined, interval?: number | undefined}; export type GetApiFreeSlotsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiFreeSlotsResponse = z.object({data: z.array(z.object({practitionerId: z.number().int().gt(0), slots: z.array(z.object({start: z.string(), end: z.string()}))}))}); 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 }; /** * Search for free slots * * GET /free-slots */ export const getApiFreeSlots = async (args: GetApiFreeSlotsArgs, options?: GetApiFreeSlotsOptions) => { const {baseUrl = "https://api.splose.com/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.serviceId != null) query.append("serviceId", String(args.serviceId)) if (args.locationId != null) query.append("locationId", String(args.locationId)) for (const item of args.practitionerIds ?? []) query.append("practitionerIds", String(item)) if (args.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) if (args.interval != null) query.append("interval", String(args.interval)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/free-slots${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(getApiFreeSlotsResponse, await res.json()) };