import {z} from 'zod' export type Country = string; export type GetApiCustomerArgs = {country?: Country | undefined, tax_id?: string | undefined, tax_id_type?: ('rfc' | 'cnpj' | 'cpf' | 'ruc' | 'curp' | 'le' | 'dni' | 'lm' | 'pas' | 'ce' | 'nit' | 'cc' | 'pa' | 'ti' | 'nuip' | 'ppt' | 'pep' | 'cuil' | 'cuit' | 'other') | undefined, external_id?: string | undefined}; export type GetApiCustomerOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const customerResponse = z.object({name: z.string().max(200), document_type: z.string().max(100).nullable().optional(), document_number: z.string().max(100).nullable().optional(), email: z.string().max(254).nullable().optional(), id: z.string()}); export const getApiCustomerResponse = z.object({count: z.number().int().optional(), next: z.string().optional(), previous: z.string().optional(), results: z.array(customerResponse).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 the customers * * GET /customer */ export const getApiCustomer = async (args: GetApiCustomerArgs, options: GetApiCustomerOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.country != null) query.append("country", String(args.country)) if (args.tax_id != null) query.append("tax_id", String(args.tax_id)) if (args.tax_id_type != null) query.append("tax_id_type", String(args.tax_id_type)) if (args.external_id != null) query.append("external_id", String(args.external_id)) const url = `${baseUrl.replace(/\/+$/, '')}/customer${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(getApiCustomerResponse, await res.json()) };