import {z} from 'zod' export type EdubankBuyersAddress = {city: string, additional_information?: string | undefined, number: string, state_code: string, street: string, neighborhood: string, zip: string, country_code: 'BR'}; export type EdubankBuyerDto = {first_name: string, last_name: string, email?: string | undefined, taxpayer_id: string, birthdate?: string | undefined, phone_number?: string | undefined, address: EdubankBuyersAddress}; export type CreateApiV1BuyersArgs = {body: EdubankBuyerDto}; export type CreateApiV1BuyersOptions = {baseUrl: string, xApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const edubankBuyersAddress = z.object({city: z.string(), additional_information: z.string().optional(), number: z.string(), state_code: z.string(), street: z.string(), neighborhood: z.string(), zip: z.string(), country_code: z.literal("BR")}); export const edubankBuyers = z.object({id: z.string().optional(), first_name: z.string(), last_name: z.string(), email: z.string().optional(), taxpayer_id: z.string(), birthdate: z.string().optional(), phone_number: z.string().optional(), address: edubankBuyersAddress}); 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 }; /** * Register a new buyer * * POST /v1/buyers * * Also accepts auth: authorization */ export const createApiV1Buyers = async (args: CreateApiV1BuyersArgs, options: CreateApiV1BuyersOptions) => { const {baseUrl, fetch: fetchFn = fetch, xApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (xApiKey !== undefined) headers.set("x-api-key", xApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/buyers${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(edubankBuyers, await res.json()) };