Files
hereconnect/packages/tg-bot-webhook-ddoc/src/updates/saveUpdate.ts
T

53 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-12-10 13:21:38 +02:00
import { TelegramWebhookDesignDocument, TgUpdateDocument } from "../types";
export type { TelegramWebhookDesignDocument };
type CouchRequest = {
body: string; // JSON-строка
headers: Record<string, string>; // Заголовки запроса
method: string; // HTTP-метод (обычно POST для update handlers)
query: Record<string, string>; // Параметры запроса (например, ?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();