import {z} from 'zod' export type GetApiCompanyOptions = {baseUrl?: string | undefined, oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const company = z.object({guid: z.string(), prefix: z.string(), name: z.string().nullable(), dateCreated: z.string(), active: z.boolean(), hasTermsOfTrade: z.boolean(), hasLogo: z.boolean(), contact: z.object({firstName: z.string().nullable(), lastName: z.string().nullable(), position: z.string().nullable(), companyName: z.string().nullable(), address1: z.string().nullable(), address2: z.string().nullable(), addressSuburb: z.string().nullable(), addressCity: z.string().nullable(), addressRegion: z.string().nullable(), addressPostcode: z.string().nullable(), addressCountry: z.string().nullable(), contactItems: z.array(z.object({contactType: z.string(), contactValue: z.string()}))}).nullable(), settings: z.array(z.object({settingKey: z.string(), settingValue: z.string()})), tax: z.object({rate: z.number(), type: z.string()}).nullable()}); export const getCompanyResponse = z.object({result: z.string(), data: company}); 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 }; /** * Returns company information for the authenticated company. * * GET /company * * Also accepts auth: PersonalAccessToken */ export const getApiCompany = async (options?: GetApiCompanyOptions) => { const {baseUrl = "https://api.fergus.com", fetch: fetchFn = fetch, oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (oauth2 !== undefined) headers.set('authorization', `Bearer ${oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/company${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(getCompanyResponse, await res.json()) };