import {z} from 'zod' export type GetApiPollsPollIdResponsesArgs = {poll_id: number, limit?: number | undefined, offset?: number | undefined}; export type GetApiPollsPollIdResponsesOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const pollAnswerResponse = z.object({question_id: z.number().int().nullable(), question_text: z.string().nullable(), option_id: z.number().int().nullable(), option_text: z.string().nullable(), created_at: z.string()}); export const pollUserResponse = z.object({id: z.number().int(), user_id: z.number().int().nullable(), user_telegram_id: z.number().int().nullable(), user_username: z.string().nullable(), sent_at: z.string(), started_at: z.string().nullable(), completed_at: z.string().nullable(), reward_given: z.boolean(), reward_amount_kopeks: z.number().int(), reward_amount_rubles: z.number(), answers: z.array(pollAnswerResponse)}); export const pollResponsesListResponse = z.object({items: z.array(pollUserResponse), total: z.number().int(), limit: z.number().int(), offset: z.number().int()}); 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 Poll Responses * * GET /polls/{poll_id}/responses */ export const getApiPollsPollIdResponses = async (args: GetApiPollsPollIdResponsesArgs, options: GetApiPollsPollIdResponsesOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) if (APIKeyHeader !== undefined) headers.set("X-API-Key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/polls/${encodeURIComponent(String(args.poll_id))}/responses${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(pollResponsesListResponse, await res.json()) };