import {z} from 'zod' export type GetApiFundersArgs = {filter?: string | undefined, cursor?: string | undefined, query?: string | undefined, rows?: number | undefined, mailto?: string | undefined, offset?: number | undefined}; export type GetApiFundersOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const query = z.object({"start-index": z.number().int(), "search-terms": z.number().int()}); export const funder = z.object({id: z.string(), location: z.string(), name: z.string(), "alt-names": z.array(z.string()), uri: z.string(), replaces: z.array(z.string()), "replaced-by": z.array(z.string()), tokens: z.array(z.string())}); export const funders = z.object({"items-per-page": z.number().int(), query: query, "total-results": z.number().int(), items: z.array(funder)}); export const fundersMessage = z.object({status: z.string(), "message-type": z.string(), "message-version": z.string(), message: funders}); 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 }; /** * Returns a list of all funders in the [Funder Registry](https://gitlab.com/crossref/open_funder_registry). * * GET /funders */ export const getApiFunders = async (args: GetApiFundersArgs, options: GetApiFundersOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.filter != null) query.append("filter", String(args.filter)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.query != null) query.append("query", String(args.query)) if (args.rows != null) query.append("rows", String(args.rows)) if (args.mailto != null) query.append("mailto", String(args.mailto)) if (args.offset != null) query.append("offset", String(args.offset)) const url = `${baseUrl.replace(/\/+$/, '')}/funders${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(fundersMessage, await res.json()) };