import { TelegramWebhookDesignDocument, TgUpdateDocument } from "../types"; export type { TelegramWebhookDesignDocument }; type CouchRequest = { body: string; // JSON-строка headers: Record; // Заголовки запроса method: string; // HTTP-метод (обычно POST для update handlers) query: Record; // Параметры запроса (например, ?key=value) userCtx: { name: string | null; // Имя пользователя, если используется аутентификация roles: string[]; // Роли пользователя }; }; type CouchResponse = [ TgUpdateDocument | null, { code: number; body: string } | string, ]; type UpdateFunction = ( doc: TgUpdateDocument | null, req: CouchRequest, ) => CouchResponse; export const saveUpdate: UpdateFunction = function ( this: TelegramWebhookDesignDocument, doc: TgUpdateDocument | null, req: CouchRequest, ): CouchResponse { const token = req.headers["X-Telegram-Bot-Api-Secret-Token"]; if (token !== this.constants.telegram_secret_token) { return [null, { code: 403, body: "Forbidden: Invalid token" }]; } const data = JSON.parse(req.body); if (doc) { return [null, { code: 304, body: "Update already exists" }]; } doc = { _id: "tg_update:" + data.update_id.toString(), type: "tg_update", data: data, created_at: new Date().toISOString(), }; return [doc, "Message saved"]; }; export const saveUpdateString = saveUpdate.toString();