Supabase日志系统接入方案
背景
根据 Supabase 官方讨论 和 Supabase Management API 文档 、Supabase 日志文档,我们需要设计一个安全、高效的方案来访问 Supabase 日志,并在前端展示。
方案设计
1. 架构概述
我们采用 Edge Function 作为中间层,使用 Management API Access Token 访问 Management API,然后将日志安全地返回给前端。
前端应用 (Vue 3) -> Edge Function -> Supabase Management API
2. Edge Function 实现
在 supabase/functions/system-logs/index.ts
中实现:
// 定义日志类型枚举和对应的表名
export enum LogTable {Auth = 'auth_logs',Edge = 'edge_logs',FunctionEdge = 'function_edge_logs',Function = 'function_logs',PgBouncer = 'pgbouncer_logs',Postgres = 'postgres_logs',Postgrest = 'postgrest_logs',Realtime = 'realtime_logs',Storage = 'storage_logs',Supervisor = 'supervisor_logs'
}// 定义请求参数接口
interface LogsQueryParams {type?: string;iso_timestamp_start?: string;iso_timestamp_end?: string;
}// Supabase项目信息和访问令牌
const SUPABASE_PROJECT_ID = "your_project_id"
const SUPABASE_ACCESS_TOKEN = "your_access_token"// 处理请求的主函数
serve(async (req) => {// 处理跨域请求if (req.method === 'OPTIONS') {return new Response('ok', { headers: corsHeaders });}try {// 从请求中获取参数 (支持JSON和URL查询字符串)let params: LogsQueryParams = {};if (req.method === 'POST') {// 尝试从请求体解析JSONparams = await req.json().catch(() => ({}));}// 如果没有从请求体获取到参数,尝试从URL查询字符串获取if (Object.keys(params).length === 0) {const url = new URL(req.url);params = {type: url.searchParams.get('type') || undefined,iso_timestamp_start: url.searchParams.get('iso_timestamp_start') || undefined,iso_timestamp_end: url.searchParams.get('iso_timestamp_end') || undefined};}// 参数提取const { type, iso_timestamp_start, iso_timestamp_end } = params;// 时区处理:支持直接输入北京时间,自动转换为UTC时间const convertToUTC = (beijingTimeIso: string | undefined): string | undefined => {if (!beijingTimeIso) return undefined;try {const date = new Date(beijingTimeIso);date.setHours(date.getHours() - 8); // 减去8小时调整为UTCreturn date.toISOString();} catch (e) {return undefined;}};// 时间参数处理let startTime = convertToUTC(iso_timestamp_start) || ''