import {z} from 'zod' export type GetApiLocationIdOptions = {baseUrl?: string | undefined, DVIDS?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiLocationIdResponse = z.object({data: z.object({id: z.string(), type: z.literal("location"), attributes: z.object({name: z.string().optional(), region: z.enum(["Africa", "Antarctica", "Asia", "At Sea", "Europe", "North America", "Oceania", "South America", "In Space"]).optional(), latitude: z.string().optional(), longitude: z.string().optional()}), relationships: z.object({country: z.object({data: z.object({id: z.string(), type: z.literal("country")})}), country_subdiv: z.object({data: z.object({id: z.string(), type: z.literal("country-subdiv")})}).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 }; /** * Get a location by id * * GET /location/{id} */ export const getApiLocationId = async (options?: GetApiLocationIdOptions) => { const {baseUrl = "https://submitapi.dvidshub.net", fetch: fetchFn = fetch, DVIDS} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/vnd.api+json") if (DVIDS !== undefined) headers.set('authorization', `Bearer ${DVIDS}`) const url = `${baseUrl.replace(/\/+$/, '')}/location/${encodeURIComponent(String(args.id))}${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(getApiLocationIdResponse, await res.json()) };