import {z} from 'zod' export type GetApiV2CoursesIdArgs = {id: string}; export type GetApiV2CoursesIdOptions = {baseUrl: string, JWTAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const courseAttributes = z.object({external_id: z.string(), title: z.string(), short_description: z.string(), long_description_html: z.string(), enforce_sequential_navigation: z.boolean(), lesson_count: z.number().int(), is_published: z.boolean(), promo_image_url: z.string(), average_rating: z.number().nullable().optional(), created_at: z.string(), modified_at: z.string()}); export const courseResource = z.object({type: z.string().optional(), id: z.string(), attributes: courseAttributes, links: z.record(z.string(), z.unknown()).nullable().optional()}); export const courseDetailResponse = z.object({data: courseResource}); 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 course * * GET /v2/courses/{id} */ export const getApiV2CoursesId = async (args: GetApiV2CoursesIdArgs, options: GetApiV2CoursesIdOptions) => { const {baseUrl, fetch: fetchFn = fetch, JWTAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/vnd.api+json") if (JWTAuth !== undefined) headers.set('authorization', `Bearer ${JWTAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/courses/${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(courseDetailResponse, await res.json()) };