import {z} from 'zod' export type GetApiRefugeeCampsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const getApiRefugeeCampsResponse = z.object({"refugee-camps": z.array(z.object({area_type_en: z.string().optional(), area_type_gr: z.string().optional(), capacity: z.number().optional(), current_hosts: z.number().optional(), description: z.string().optional(), last_update: z.string().optional(), latitude: z.number().optional(), longtitude: z.number().optional(), name_en: z.string().optional(), name_gr: z.string().optional(), recorded_events: z.array(z.object({case_detection_week: z.string().optional(), confirmed_cases: z.number().optional(), quarantine_duration_days: z.number().optional(), samples: z.number().optional()})).optional(), region_en: z.string().optional(), region_gr: z.string().optional(), total_confirmed_cases: z.number().optional(), total_confirmed_samples: z.number().optional()})).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 }; /** * Recorded cases in Refugee Camps * * GET /refugee-camps */ export const getApiRefugeeCamps = async (options: GetApiRefugeeCampsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/refugee-camps${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(getApiRefugeeCampsResponse, await res.json()) };