39 lines
1.7 KiB
TypeScript
39 lines
1.7 KiB
TypeScript
import { Config } from "./config.ts";
|
|
import { defaultHeaders, notFound, secretHeader } from "./const.ts";
|
|
import { TgUpdate } from "./models.ts";
|
|
import { initDb } from "./db.ts";
|
|
import { reaction } from "./bot.ts";
|
|
|
|
export async function initReqHandler(config: Config): Promise<(req: Request) => Promise<Response>> {
|
|
const dbClient = await initDb(config);
|
|
const hostUrl = new URL(config.webhookUrl);
|
|
return async (req: Request) => {
|
|
const reqUrl = new URL(req.url);
|
|
if (reqUrl.pathname !== hostUrl.pathname || req.headers.get(secretHeader) !== config.tgSecretToken) {
|
|
return notFound;
|
|
}
|
|
|
|
try {
|
|
const update: TgUpdate = await req.json();
|
|
if (update.message?.chat.id !== config.tgChatId) {
|
|
console.error({ msg: "Invalid chat id?", update: update })
|
|
return notFound;
|
|
}
|
|
|
|
const value = parseFloat(update.message?.text || "NaN");
|
|
const userId = update.message?.from?.id;
|
|
|
|
if (!isNaN(value) && userId) {
|
|
await dbClient.queryArray`INSERT INTO fat_data (ts, value, user_id) VALUES (CURRENT_TIMESTAMP, ${value}, ${userId})`;
|
|
return new Response(reaction(true, update.message.chat.id, update.message.message_id), { headers: defaultHeaders });
|
|
} else {
|
|
console.error({ msg: "Message text is not a valid number or user ID is undefined.", update: update });
|
|
return new Response(reaction(false, update.message.chat.id, update.message.message_id), { headers: defaultHeaders });
|
|
}
|
|
} catch (e) {
|
|
console.error({ msg: "Error handling request", err: e });
|
|
}
|
|
|
|
return notFound;
|
|
};
|
|
}
|