import {z} from 'zod' export type StudentCreateRequest = {email: string, first_name?: string | undefined, last_name?: string | undefined}; export type StudentCreateData = {type: 'students', attributes: StudentCreateRequest}; export type StudentCreateRequestEnvelope = {data: Array}; export type CreateApiV2StudentsArgs = {body: StudentCreateRequestEnvelope}; export type CreateApiV2StudentsOptions = {baseUrl: string, JWTAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const studentAttributes = z.object({email: z.string(), first_name: z.string(), last_name: z.string(), is_inactive: z.boolean(), external_id: z.string(), date_joined: z.string()}); export const studentResource = z.object({type: z.string().optional(), id: z.string(), attributes: studentAttributes, relationships: z.record(z.string(), z.unknown()).nullable().optional(), links: z.record(z.string(), z.unknown()).nullable().optional()}); export const batchSucceededItemStudentResource = z.object({status: z.literal("succeeded").optional(), id: z.string().nullable().optional(), result: studentResource}); export const batchItemError = z.object({code: z.enum(["duplicate_email", "duplicate_in_batch", "duplicate_name", "validation_error", "not_found", "internal_error", "not_in_domain", "already_enrolled", "already_published", "already_in_path"]), source: z.record(z.string(), z.unknown()).nullable().optional(), detail: z.string().nullable().optional()}); export const batchFailedItem = z.object({status: z.literal("failed").optional(), id: z.string().nullable().optional(), error: batchItemError}); export const batchSummary = z.object({total: z.number().int().gte(0), succeeded: z.number().int().gte(0), failed: z.number().int().gte(0)}); export const batchResultEnvelopeStudentResource = z.object({data: z.array(z.union([batchSucceededItemStudentResource, batchFailedItem])), summary: batchSummary}); 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 students * * POST /v2/students/ */ export const createApiV2Students = async (args: CreateApiV2StudentsArgs, options: CreateApiV2StudentsOptions) => { const {baseUrl, fetch: fetchFn = fetch, JWTAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/vnd.api+json") if (JWTAuth !== undefined) headers.set('authorization', `Bearer ${JWTAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/students/${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(batchResultEnvelopeStudentResource, await res.json()) };