import {z} from 'zod' export type GetApiV1FieldsArgs = {category: 'AGENT' | 'ATTACHMENT' | 'CONTACT' | 'CUSTOMER' | 'SERVICE_PRODUCT' | 'INVENTORY' | 'INVENTORY_TYPE' | 'LINE' | 'NOTE' | 'ORDER' | 'PRODUCT' | 'REQUEST_SERVICE' | 'TASK' | 'TICKET', type_id?: number | undefined}; export type GetApiV1FieldsOptions = {baseUrl?: string | undefined, basic?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const revAppComponentsLink = z.object({rel: z.string().optional(), href: z.string().optional()}); export const revAppModelsField = z.object({field_id: z.number().int().optional(), label: z.string().optional(), description: z.string().optional(), default_value: z.string().optional(), required: z.string().optional(), links: z.array(revAppComponentsLink).optional()}); export const revAppModelsFieldResult = z.object({Fields: z.array(revAppModelsField).optional(), links: z.array(revAppComponentsLink).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 }; /** * View defined custom fields. * * GET /v1/Fields */ export const getApiV1Fields = async (args: GetApiV1FieldsArgs, options?: GetApiV1FieldsOptions) => { const {baseUrl = "https://restapi.rev.io", fetch: fetchFn = fetch, basic} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.category != null) query.append("category", String(args.category)) if (args.type_id != null) query.append("type_id", String(args.type_id)) if (basic !== undefined) headers.set('authorization', `Basic ${btoa(`${basic.username}:${basic.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/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(revAppModelsFieldResult, await res.json()) };