48 lines
1.4 KiB
TypeScript
48 lines
1.4 KiB
TypeScript
import { fail, handleOptions, json } from "../_shared/http.ts";
|
|
import { requireUser } from "../_shared/supabase.ts";
|
|
|
|
Deno.serve(async (req) => {
|
|
const preflight = handleOptions(req);
|
|
if (preflight) return preflight;
|
|
|
|
if (req.method !== "POST") return fail("Method not allowed", 405);
|
|
|
|
const { client, user, error: userError } = await requireUser(req);
|
|
if (!user) return fail(userError ?? "Unauthorized", 401);
|
|
|
|
let body: { channel_id?: string; before?: string; limit?: number };
|
|
try {
|
|
body = await req.json();
|
|
} catch {
|
|
return fail("Invalid JSON body");
|
|
}
|
|
|
|
const channelId = body.channel_id;
|
|
if (!channelId) return fail("channel_id is required");
|
|
|
|
const limit = Math.max(1, Math.min(Number(body.limit) || 50, 100));
|
|
const before = body.before?.trim();
|
|
|
|
let query = client
|
|
.from("messages")
|
|
.select("id, channel_id, author_user_id, content, created_at, edited_at")
|
|
.eq("channel_id", channelId)
|
|
.is("deleted_at", null)
|
|
.order("created_at", { ascending: false })
|
|
.limit(limit);
|
|
|
|
if (before) {
|
|
query = query.lt("created_at", before);
|
|
}
|
|
|
|
const { data: rows, error } = await query;
|
|
if (error) {
|
|
if (error.code === "42501") return fail("forbidden", 403);
|
|
return fail(error.message, 400);
|
|
}
|
|
|
|
return json({
|
|
messages: (rows ?? []).reverse(),
|
|
next_before: rows && rows.length > 0 ? rows[rows.length - 1].created_at : null,
|
|
});
|
|
});
|