import {z} from 'zod' export type GetApiV1SpeciesUsageKeyIucnRedListCategoryArgs = {usageKey: number}; export type GetApiV1SpeciesUsageKeyIucnRedListCategoryOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const iucnRedListCategory = z.object({category: z.enum(["EXTINCT", "EXTINCT_IN_THE_WILD", "REGIONALLY_EXTINCT", "CRITICALLY_ENDANGERED", "ENDANGERED", "VULNERABLE", "NEAR_THREATENED", "LEAST_CONCERN", "DATA_DEFICIENT", "NOT_APPLICABLE", "NOT_EVALUATED"]).optional(), usageKey: z.number().int().optional(), scientificName: z.string().optional(), taxonomicStatus: z.enum(["ACCEPTED", "DOUBTFUL", "SYNONYM", "HETEROTYPIC_SYNONYM", "HOMOTYPIC_SYNONYM", "PROPARTE_SYNONYM", "MISAPPLIED"]).optional(), acceptedName: z.string().optional(), acceptedUsageKey: z.number().int().optional(), iucnTaxonID: z.string().optional(), code: z.string().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 }; /** * IUCN Red List Category for a name usage * * GET /v1/species/{usageKey}/iucnRedListCategory */ export const getApiV1SpeciesUsageKeyIucnRedListCategory = async (args: GetApiV1SpeciesUsageKeyIucnRedListCategoryArgs, options?: GetApiV1SpeciesUsageKeyIucnRedListCategoryOptions) => { const {baseUrl = "https://api.gbif.org", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/species/${encodeURIComponent(String(args.usageKey))}/iucnRedListCategory${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(iucnRedListCategory, await res.json()) };