import {z} from 'zod' export type GetApiAuthorIdOptions = {baseUrl?: string | undefined, DVIDS?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiAuthorIdResponse = z.object({data: z.object({id: z.string(), type: z.literal("author"), attributes: z.object({name: z.string(), job_grade: z.object({name: z.string(), associated_press_name: z.string(), abbreviation: z.string(), branch: z.enum(["army", "navy", "air-force", "marines", "coast-guard", "joint"]).nullable().optional(), job_grade: z.string().nullable().optional(), nato_code: z.string().nullable().optional(), country_code: z.string().nullable().optional()}).optional(), vision_id: z.string().nullable()}), relationships: z.object({service_units: z.object({data: z.array(z.object({id: z.string(), type: z.literal("service-unit")}))})})})}); 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 an author by id * * GET /author/{id} */ export const getApiAuthorId = async (options?: GetApiAuthorIdOptions) => { 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(/\/+$/, '')}/author/${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(getApiAuthorIdResponse, await res.json()) };