mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 09:31:13 -05:00
Migrate Novu functions to wrapEdgeFunction
Refactor Phase 3 Batch 2–4 Novu-related functions to use the createEdgeFunction wrapper, replacing explicit HTTP servers with edge wrapper, adding standardized logging, tracing, and error handling across subscriber management, topic/notification, and migration/sync functions.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
|
||||
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { edgeLogger } from "../_shared/logger.ts";
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
interface AnnouncementPayload {
|
||||
title: string;
|
||||
@@ -10,38 +10,25 @@ interface AnnouncementPayload {
|
||||
actionUrl?: string;
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest('notify-system-announcement');
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'notify-system-announcement',
|
||||
requireAuth: true,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||
|
||||
// Get authorization header
|
||||
const authHeader = req.headers.get('authorization');
|
||||
if (!authHeader) {
|
||||
throw new Error('Authorization header required');
|
||||
}
|
||||
|
||||
// Verify user is admin or superuser
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
const { data: { user }, error: authError } = await supabase.auth.getUser(token);
|
||||
|
||||
if (authError || !user) {
|
||||
throw new Error('Unauthorized: Invalid token');
|
||||
}
|
||||
context.span.setAttribute('action', 'notify_system_announcement');
|
||||
|
||||
// Check user role
|
||||
const { data: roles, error: roleError } = await supabase
|
||||
.from('user_roles')
|
||||
.select('role')
|
||||
.eq('user_id', user.id)
|
||||
.eq('user_id', context.userId)
|
||||
.in('role', ['admin', 'superuser']);
|
||||
|
||||
if (roleError || !roles || roles.length === 0) {
|
||||
@@ -52,7 +39,7 @@ serve(async (req) => {
|
||||
const { data: profile } = await supabase
|
||||
.from('profiles')
|
||||
.select('username, display_name')
|
||||
.eq('user_id', user.id)
|
||||
.eq('user_id', context.userId)
|
||||
.single();
|
||||
|
||||
const payload: AnnouncementPayload = await req.json();
|
||||
@@ -71,7 +58,7 @@ serve(async (req) => {
|
||||
title: payload.title,
|
||||
severity: payload.severity,
|
||||
publishedBy: profile?.username || 'unknown',
|
||||
requestId: tracking.requestId
|
||||
requestId: context.requestId
|
||||
});
|
||||
|
||||
// Fetch the workflow ID for system announcements
|
||||
@@ -83,22 +70,13 @@ serve(async (req) => {
|
||||
.maybeSingle();
|
||||
|
||||
if (templateError) {
|
||||
edgeLogger.error('Error fetching workflow', { action: 'notify_system_announcement', requestId: tracking.requestId, error: templateError });
|
||||
edgeLogger.error('Error fetching workflow', { action: 'notify_system_announcement', requestId: context.requestId, error: templateError });
|
||||
throw new Error(`Failed to fetch workflow: ${templateError.message}`);
|
||||
}
|
||||
|
||||
if (!template) {
|
||||
edgeLogger.warn('No active system-announcement workflow found', { action: 'notify_system_announcement', requestId: tracking.requestId });
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'No active system-announcement workflow configured',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
edgeLogger.warn('No active system-announcement workflow found', { action: 'notify_system_announcement', requestId: context.requestId });
|
||||
throw new Error('No active system-announcement workflow configured');
|
||||
}
|
||||
|
||||
const announcementId = crypto.randomUUID();
|
||||
@@ -117,7 +95,7 @@ serve(async (req) => {
|
||||
publishedBy,
|
||||
};
|
||||
|
||||
edgeLogger.info('Triggering announcement to all users via "users" topic', { action: 'notify_system_announcement', requestId: tracking.requestId });
|
||||
edgeLogger.info('Triggering announcement to all users via "users" topic', { action: 'notify_system_announcement', requestId: context.requestId });
|
||||
|
||||
// Invoke the trigger-notification function with users topic
|
||||
const { data: result, error: notifyError } = await supabase.functions.invoke(
|
||||
@@ -132,13 +110,11 @@ serve(async (req) => {
|
||||
);
|
||||
|
||||
if (notifyError) {
|
||||
edgeLogger.error('Error triggering notification', { action: 'notify_system_announcement', requestId: tracking.requestId, error: notifyError });
|
||||
edgeLogger.error('Error triggering notification', { action: 'notify_system_announcement', requestId: context.requestId, error: notifyError });
|
||||
throw notifyError;
|
||||
}
|
||||
|
||||
edgeLogger.info('System announcement triggered successfully', { action: 'notify_system_announcement', requestId: tracking.requestId, result });
|
||||
|
||||
endRequest(tracking, 200);
|
||||
edgeLogger.info('System announcement triggered successfully', { action: 'notify_system_announcement', requestId: context.requestId, result });
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
@@ -146,36 +122,13 @@ serve(async (req) => {
|
||||
transactionId: result?.transactionId,
|
||||
announcementId,
|
||||
payload: notificationPayload,
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error: any) {
|
||||
edgeLogger.error('Error in notify-system-announcement', { action: 'notify_system_announcement', requestId: tracking.requestId, error: error.message });
|
||||
|
||||
endRequest(tracking, error.message.includes('Unauthorized') ? 403 : 500, error.message);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: error.message,
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: error.message.includes('Unauthorized') ? 403 : 500,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user