import {z} from 'zod' export type GetApiV2LearnQuizArgs = {Authorization: string, uuid: string, word_id: string}; export type GetApiV2LearnQuizOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const bluenteInternalCourseV2ModelLearnQuizOptions = z.object({answer: z.boolean().optional(), id: z.number().int().optional(), illustration: z.string().optional(), speech: z.string().optional(), word: z.string().optional()}); export const bluenteInternalCourseV2ModelLearnQuiz = z.object({answer_id: z.number().int().optional(), options: z.array(bluenteInternalCourseV2ModelLearnQuizOptions).optional(), question: z.string().optional()}); export const getApiV2LearnQuizResponse = z.object({code: z.number().int().optional(), data: z.array(bluenteInternalCourseV2ModelLearnQuiz).optional(), message: z.string().optional()}); 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 quiz associate with the word. * * GET /v2/learn/quiz */ export const getApiV2LearnQuiz = async (args: GetApiV2LearnQuizArgs, options: GetApiV2LearnQuizOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args.uuid != null) query.append("uuid", String(args.uuid)) if (args.word_id != null) query.append("word_id", String(args.word_id)) const url = `${baseUrl.replace(/\/+$/, '')}/v2/learn/quiz${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(getApiV2LearnQuizResponse, await res.json()) };