import {z} from 'zod' export type SortAscDescDefaultDesc = 'asc' | 'desc'; export type SortAscDesc = 'asc' | 'desc'; export type GetApiCustomObjectsArgs = {key: string, start_cursor?: string | undefined, per_page?: number | undefined, sort?: ({id?: SortAscDescDefaultDesc | undefined, created_at?: SortAscDesc | undefined, updated_at?: SortAscDesc | undefined}) | undefined}; export type GetApiCustomObjectsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, accountToken?: string | undefined, fetch?: typeof fetch | undefined}; export const sortAscDesc = z.enum(["asc", "desc"]); export const customFields = z.object({}).nullable(); export const customObjectCustomFieldAssociation = z.object({custom_field_id: z.number().int(), id: z.number().int(), reference_id: z.number().int(), reference_type: z.enum(["Contact", "Equipment", "Vehicle", "Vendor"]), reference: z.union([z.object({id: z.number().int().optional(), email: z.string().nullable().optional(), name: z.string().nullable().optional(), group_id: z.number().int().nullable().optional(), employee: z.boolean().nullable().optional(), employee_number: z.string().nullable().optional(), default_image_url: z.string().nullable().optional()}).nullable(), z.object({id: z.number().int(), name: z.string(), color: z.string().nullable().optional(), license_plate: z.string().nullable().optional(), vin: z.string().nullable().optional(), year: z.string().nullable().optional(), make: z.string().nullable().optional(), model: z.string().nullable().optional(), trim: z.string().nullable().optional(), registration_expiration_month: z.number().int().gte(0).lte(12).nullable().optional(), registration_state: z.string().nullable().optional(), default_image_url_small: z.string().nullable().optional()}), z.object({name: z.string(), phone: z.string().nullable(), city: z.string().nullable(), region: z.string().nullable(), postal_code: z.string().nullable(), country: z.string().nullable(), external_id: z.string().nullable()}).nullable(), z.object({id: z.number().int(), name: z.string(), brand: z.string().nullable(), model: z.string().nullable(), serial_number: z.string().nullable()}).nullable()]).nullable().optional()}); export const attachmentPermissions = z.object({read_photos: z.boolean().optional(), manage_photos: z.boolean().optional(), read_documents: z.boolean().optional(), manage_documents: z.boolean().optional()}).nullable(); export const customObjectPermissions = z.object({update: z.boolean(), destroy: z.boolean()}); export const customObject = z.object({id: z.number().int(), custom_object_template_id: z.number().int(), created_at: z.string(), custom_fields: customFields, updated_at: z.string(), comments_count: z.number().int().gte(0), documents_count: z.number().int().gte(0), images_count: z.number().int().gte(0), custom_field_associations: z.array(customObjectCustomFieldAssociation), attachment_permissions: attachmentPermissions, permissions: customObjectPermissions}); export const getApiCustomObjectsResponse = z.object({start_cursor: z.string().nullable().optional(), next_cursor: z.string().nullable().optional(), per_page: z.number().int().optional(), estimated_remaining_count: z.number().int().optional(), sorted_by: z.array(z.union([z.object({id: sortAscDesc.optional()}), z.object({created_at: sortAscDesc.optional()}), z.object({updated_at: sortAscDesc.optional()})])).optional(), records: z.array(customObject).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 }; /** * List Custom Objects * * GET /custom_objects */ export const getApiCustomObjects = async (args: GetApiCustomObjectsArgs, options?: GetApiCustomObjectsOptions) => { const {baseUrl = "https://secure.fleetio.com/api", fetch: fetchFn = fetch, apiKey, accountToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.key != null) query.append("key", String(args.key)) if (args.start_cursor != null) query.append("start_cursor", String(args.start_cursor)) if (args.per_page != null) query.append("per_page", String(args.per_page)) if (args.sort != null) query.append("sort", JSON.stringify(args.sort)) if (apiKey !== undefined) headers.set("Authorization", apiKey) if (accountToken !== undefined) headers.set("Account-Token", accountToken) const url = `${baseUrl.replace(/\/+$/, '')}/custom_objects${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(getApiCustomObjectsResponse, await res.json()) };