import {z} from 'zod' export type GetApiCustomFieldsArgs = {Authorization: string, section?: ('personal' | 'work' | 'address' | 'financial' | 'home') | undefined, label?: string | undefined, apiName?: string | undefined}; export type GetApiCustomFieldsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiCustomFieldsResponse = z.object({data: z.array(z.object({_id: z.string().optional(), section: z.string().optional(), label: z.string().optional(), apiName: z.string().optional(), type: z.string().optional(), values: z.array(z.string()).optional()})).optional()}); 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 }; /** * Return a list of custome fields. * * GET /custom-fields */ export const getApiCustomFields = async (args: GetApiCustomFieldsArgs, options?: GetApiCustomFieldsOptions) => { const {baseUrl = "https://sandbox-api.kenjo.io/api/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args.section != null) query.append("section", String(args.section)) if (args.label != null) query.append("label", String(args.label)) if (args.apiName != null) query.append("apiName", String(args.apiName)) const url = `${baseUrl.replace(/\/+$/, '')}/custom-fields${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(getApiCustomFieldsResponse, await res.json()) };