import {z} from 'zod' export type GetApiExamsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const placeRef = z.object({buildingId: z.string(), floorId: z.string(), roomId: z.string(), siteId: z.string(), name: z.string()}); export const exam = z.object({id: z.number().int(), courseId: z.number(), courseShortcode: z.string(), courseName: z.string(), teacherId: z.number().int(), type: z.string(), places: z.array(placeRef).optional(), status: z.enum(["available", "booked", "requestable", "requested", "requestAccepted", "requestRejected", "unavailable"]), bookingStartsAt: z.string().nullable(), bookingEndsAt: z.string(), examStartsAt: z.string().nullable(), examEndsAt: z.string().nullable(), bookedCount: z.number().int(), availableCount: z.number().int(), question: z.object({id: z.number().int(), statement: z.string(), options: z.array(z.string())}).nullable(), feedback: z.string().nullable(), isReschedulable: z.boolean(), notes: z.string().nullable(), moduleNumber: z.number().int(), requestReason: z.string().nullable(), requestDetails: z.string().nullable()}); export const getApiExamsResponse = z.object({data: z.array(exam)}); 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 }; /** * List exams | Elenca esami * * GET /exams */ export const getApiExams = async (options?: GetApiExamsOptions) => { const {baseUrl = "https://app.didattica.polito.it/api", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/exams${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(getApiExamsResponse, await res.json()) };