import {z} from 'zod' export type PollOptionCreate = {text: string}; export type PollQuestionCreate = {text: string, options: Array}; export type PollCreateRequest = {title: string, description?: (string | null) | undefined, reward_enabled?: boolean | undefined, reward_amount_kopeks?: number | undefined, questions: Array}; export type CreateApiPollsArgs = {body: PollCreateRequest}; export type CreateApiPollsOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const pollQuestionOptionResponse = z.object({id: z.number().int(), text: z.string(), order: z.number().int()}); export const appWebapiSchemasPollsPollQuestionResponse = z.object({id: z.number().int(), text: z.string(), order: z.number().int(), options: z.array(pollQuestionOptionResponse)}); export const pollDetailResponse = z.object({id: z.number().int(), title: z.string(), description: z.string().nullable(), reward_enabled: z.boolean(), reward_amount_kopeks: z.number().int(), reward_amount_rubles: z.number(), questions: z.array(appWebapiSchemasPollsPollQuestionResponse), created_at: z.string(), updated_at: z.string()}); 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 Poll Endpoint * * POST /polls */ export const createApiPolls = async (args: CreateApiPollsArgs, options: CreateApiPollsOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (APIKeyHeader !== undefined) headers.set("X-API-Key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/polls${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(pollDetailResponse, await res.json()) };