link-stack/packages/bridge-ui/lib/whatsapp.ts

61 lines
1.9 KiB
TypeScript
Raw Permalink Normal View History

2024-05-16 18:22:10 +02:00
import { NextResponse } from "next/server";
2024-06-05 08:52:41 +02:00
import { db } from "@link-stack/bridge-common";
2024-05-16 18:22:10 +02:00
import { revalidatePath } from "next/cache";
import { Service, ServiceParams } from "./service";
2024-04-30 11:39:16 +02:00
2024-05-16 18:22:10 +02:00
export class Whatsapp extends Service {
2024-11-25 09:31:25 +01:00
async getBot({ params }: ServiceParams) {
const { token } = await params;
2024-05-16 18:22:10 +02:00
const row = await db
.selectFrom("WhatsappBot")
.selectAll()
.where("token", "=", token as string)
.executeTakeFirstOrThrow();
const id = row.id;
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}`;
const result = await fetch(url, { cache: "no-store" });
const json = await result.json();
await db
.updateTable("WhatsappBot")
.set({ verified: json.verified })
.where("id", "=", id)
.execute();
if (!json.verified) {
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}/register`;
2024-05-17 09:20:00 +02:00
const result = await fetch(url, { method: "POST" });
2024-05-16 18:22:10 +02:00
}
2024-05-17 09:20:00 +02:00
revalidatePath(`/whatsapp/${id}`);
2024-05-16 18:22:10 +02:00
return NextResponse.json(json);
}
2025-11-09 11:12:04 +01:00
async relink({ params }: ServiceParams) {
const { token } = await params;
const row = await db
.selectFrom("WhatsappBot")
.selectAll()
.where("token", "=", token as string)
.executeTakeFirstOrThrow();
const id = row.id;
// Step 1: Call unverify to remove the bot directory and disconnect
const unverifyUrl = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}/unverify`;
await fetch(unverifyUrl, { method: "POST" });
// Step 2: Reset verified flag in database
await db
.updateTable("WhatsappBot")
.set({ verified: false })
.where("id", "=", id)
.execute();
// Step 3: Revalidate the path to refresh the UI
revalidatePath(`/whatsapp/${id}`);
return NextResponse.json({ success: true, message: "WhatsApp connection reset. Please scan the new QR code." });
}
2024-05-16 18:22:10 +02:00
}