import {z} from 'zod' export type GetApiProjectsArgs = {search?: string | undefined, sort?: ('default' | '+default' | '-default' | 'project_name' | '+project_name' | '-project_name' | 'obs_count' | '+obs_count' | '-obs_count') | undefined, limit?: number | undefined, offset?: number | undefined, create_parquet?: boolean | undefined}; export type GetApiProjectsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const project = z.object({pj_code: z.string().optional(), project_name: z.string().optional(), project_description: z.string().optional(), start_date: z.string().optional(), stop_date: z.string().optional(), obs_count: z.number().int().optional(), last_plot_added_date: 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 }; /** * Get all projects * * GET /projects */ export const getApiProjects = async (args: GetApiProjectsArgs, options?: GetApiProjectsOptions) => { const {baseUrl = "https://api.vegbank.org", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.search != null) query.append("search", String(args.search)) if (args.sort != null) query.append("sort", String(args.sort)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) if (args.create_parquet != null) query.append("create_parquet", String(args.create_parquet)) const url = `${baseUrl.replace(/\/+$/, '')}/projects${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(project, await res.json()) };