import {z} from 'zod' export type GetApiV2IndustriesSimilarArgs = {industries: Array, page?: number | undefined, size?: number | undefined}; export type GetApiV2IndustriesSimilarOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const paginationMeta = z.object({cost: z.number(), credits: z.number(), currentPage: z.number(), firstPage: z.number(), freeRequest: z.boolean(), lastPage: z.number(), maxScrollResultsReached: z.boolean().optional(), perPage: z.number(), total: z.number()}); export const getApiV2IndustriesSimilarResponse = z.object({industries: z.array(z.object({companiesCount: z.number().nullable(), name: z.string(), slug: z.unknown()})), meta: paginationMeta}); 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 }; /** * Get similar industries from one or many industries. * * GET /v2/industries/similar */ export const getApiV2IndustriesSimilar = async (args: GetApiV2IndustriesSimilarArgs, options?: GetApiV2IndustriesSimilarOptions) => { const {baseUrl = "https://api.thecompaniesapi.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.industries ?? []) query.append("industries", String(item)) if (args.page != null) query.append("page", String(args.page)) if (args.size != null) query.append("size", String(args.size)) if (apiKey !== undefined) headers.set("Authorization", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v2/industries/similar${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(getApiV2IndustriesSimilarResponse, await res.json()) };