eris/api/withUser.ts

40 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-10-17 13:03:14 +00:00
import { Chat } from "grammy_types";
2023-10-23 00:39:01 +00:00
import { Model } from "indexed_kv";
import { Admin, adminStore } from "../app/adminStore.ts";
2023-10-17 13:03:14 +00:00
import { bot } from "../bot/mod.ts";
import { sessions } from "./sessionsRoute.ts";
2023-11-17 23:52:51 +00:00
export async function withUser<O>(
2023-10-17 13:03:14 +00:00
query: { sessionId: string },
cb: (user: Chat.PrivateGetChat) => Promise<O>,
) {
const session = sessions.get(query.sessionId);
if (!session?.userId) {
2023-11-17 23:52:51 +00:00
throw new Error("Must be logged in");
2023-10-17 13:03:14 +00:00
}
2023-10-23 00:39:01 +00:00
const user = await getUser(session.userId);
return cb(user);
}
2023-11-17 23:52:51 +00:00
export async function withAdmin<O>(
2023-10-23 00:39:01 +00:00
query: { sessionId: string },
cb: (user: Chat.PrivateGetChat, admin: Model<Admin>) => Promise<O>,
) {
const session = sessions.get(query.sessionId);
if (!session?.userId) {
2023-11-17 23:52:51 +00:00
throw new Error("Must be logged in");
2023-10-23 00:39:01 +00:00
}
const user = await getUser(session.userId);
const [admin] = await adminStore.getBy("tgUserId", { value: session.userId });
if (!admin) {
2023-11-17 23:52:51 +00:00
throw new Error("Must be admin");
2023-10-17 13:03:14 +00:00
}
2023-10-23 00:39:01 +00:00
return cb(user, admin);
}
export async function getUser(userId: number): Promise<Chat.PrivateGetChat> {
const chat = await bot.api.getChat(userId);
if (chat.type !== "private") throw new Error("Chat is not private");
return chat;
2023-10-17 13:03:14 +00:00
}