import {z} from 'zod' export type CreateApiServiceUnitIdVirinArgs = {body: {data: {id: string, type: 'service-unit-virin', attributes: {date: string, virin?: string | undefined}, relationships: {'service-unit': {data: {id: string, type: 'service-unit'}}}}}}; export type CreateApiServiceUnitIdVirinOptions = {baseUrl?: string | undefined, DVIDS?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiServiceUnitIdVirinResponse = z.object({data: z.object({id: z.string(), type: z.literal("service-unit-virin"), attributes: z.object({date: z.string(), virin: z.string().optional()}), relationships: z.object({"service-unit": z.object({data: 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 }; /** * Create a VIRIN for a service unit * * POST /service-unit/{id}/virin */ export const createApiServiceUnitIdVirin = async (args: CreateApiServiceUnitIdVirinArgs, options?: CreateApiServiceUnitIdVirinOptions) => { const {baseUrl = "https://submitapi.dvidshub.net", fetch: fetchFn = fetch, DVIDS} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/vnd.api+json") headers.set('accept', "application/vnd.api+json") if (DVIDS !== undefined) headers.set('authorization', `Bearer ${DVIDS}`) const url = `${baseUrl.replace(/\/+$/, '')}/service-unit/${encodeURIComponent(String(args.id))}/virin${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiServiceUnitIdVirinResponse, await res.json()) };