mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-21 09:51: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,21 +1,17 @@
|
||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||
import { Novu } from "npm:@novu/api@1.6.0";
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger } from '../_shared/logger.ts';
|
||||
import { formatEdgeError } from '../_shared/errorFormatter.ts';
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { validateString } from '../_shared/typeValidation.ts';
|
||||
|
||||
// Simple request tracking
|
||||
const startRequest = () => ({ requestId: crypto.randomUUID(), start: Date.now() });
|
||||
const endRequest = (tracking: { start: number }) => Date.now() - tracking.start;
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'create-novu-subscriber',
|
||||
requireAuth: false,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const novuApiKey = Deno.env.get('NOVU_API_KEY');
|
||||
|
||||
if (!novuApiKey) {
|
||||
@@ -26,168 +22,53 @@ serve(async (req) => {
|
||||
secretKey: novuApiKey
|
||||
});
|
||||
|
||||
// Parse and validate request body
|
||||
let requestBody;
|
||||
try {
|
||||
requestBody = await req.json();
|
||||
} catch (parseError) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Invalid JSON in request body',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const { subscriberId, email, firstName, lastName, phone, avatar, data } = requestBody;
|
||||
const { subscriberId, email, firstName, lastName, phone, avatar, data } = await req.json();
|
||||
|
||||
// Validate required fields
|
||||
if (!subscriberId || typeof subscriberId !== 'string' || subscriberId.trim() === '') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'subscriberId is required and must be a non-empty string',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
validateString(subscriberId, 'subscriberId', { requestId: context.requestId });
|
||||
validateString(email, 'email', { requestId: context.requestId });
|
||||
|
||||
if (!email || typeof email !== 'string' || email.trim() === '') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'email is required and must be a non-empty string',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Validate email format using regex
|
||||
// Validate email format
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Invalid email format. Please provide a valid email address',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('Invalid email format. Please provide a valid email address');
|
||||
}
|
||||
|
||||
// Validate optional fields if provided
|
||||
if (firstName !== undefined && firstName !== null && (typeof firstName !== 'string' || firstName.length > 100)) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'firstName must be a string with maximum 100 characters',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('firstName must be a string with maximum 100 characters');
|
||||
}
|
||||
|
||||
if (lastName !== undefined && lastName !== null && (typeof lastName !== 'string' || lastName.length > 100)) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'lastName must be a string with maximum 100 characters',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('lastName must be a string with maximum 100 characters');
|
||||
}
|
||||
|
||||
if (phone !== undefined && phone !== null) {
|
||||
if (typeof phone !== 'string') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'phone must be a string',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('phone must be a string');
|
||||
}
|
||||
// Validate phone format (basic validation for international numbers)
|
||||
const phoneRegex = /^\+?[1-9]\d{1,14}$/;
|
||||
if (!phoneRegex.test(phone.replace(/[\s\-\(\)]/g, ''))) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Invalid phone format. Please provide a valid international phone number',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('Invalid phone format. Please provide a valid international phone number');
|
||||
}
|
||||
}
|
||||
|
||||
if (avatar !== undefined && avatar !== null && (typeof avatar !== 'string' || !avatar.startsWith('http'))) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'avatar must be a valid URL',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('avatar must be a valid URL');
|
||||
}
|
||||
|
||||
// Validate data field if provided
|
||||
if (data !== undefined && data !== null) {
|
||||
if (typeof data !== 'object' || Array.isArray(data)) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'data must be a valid object',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('data must be a valid object');
|
||||
}
|
||||
|
||||
// Check data size (limit to 10KB serialized)
|
||||
const dataSize = JSON.stringify(data).length;
|
||||
if (dataSize > 10240) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'data field is too large (maximum 10KB)',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('data field is too large (maximum 10KB)');
|
||||
}
|
||||
}
|
||||
|
||||
edgeLogger.info('Creating Novu subscriber', { subscriberId, email: '***', firstName, requestId: tracking.requestId });
|
||||
context.span.setAttribute('action', 'create_novu_subscriber');
|
||||
edgeLogger.info('Creating Novu subscriber', { subscriberId, email: '***', firstName, requestId: context.requestId });
|
||||
|
||||
const subscriber = await novu.subscribers.identify(subscriberId, {
|
||||
email,
|
||||
@@ -198,26 +79,24 @@ serve(async (req) => {
|
||||
data,
|
||||
});
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Subscriber created successfully', {
|
||||
subscriberId: subscriber.data._id,
|
||||
requestId: tracking.requestId,
|
||||
duration
|
||||
requestId: context.requestId
|
||||
});
|
||||
|
||||
// Add subscriber to "users" topic for global announcements
|
||||
try {
|
||||
edgeLogger.info('Adding subscriber to users topic', { subscriberId, requestId: tracking.requestId });
|
||||
edgeLogger.info('Adding subscriber to users topic', { subscriberId, requestId: context.requestId });
|
||||
await novu.topics.addSubscribers('users', {
|
||||
subscribers: [subscriberId],
|
||||
});
|
||||
edgeLogger.info('Successfully added subscriber to users topic', { subscriberId, requestId: tracking.requestId });
|
||||
edgeLogger.info('Successfully added subscriber to users topic', { subscriberId, requestId: context.requestId });
|
||||
} catch (topicError: unknown) {
|
||||
// Non-blocking - log error but don't fail the request
|
||||
edgeLogger.error('Failed to add subscriber to users topic', {
|
||||
error: formatEdgeError(topicError),
|
||||
subscriberId,
|
||||
requestId: tracking.requestId
|
||||
requestId: context.requestId
|
||||
});
|
||||
}
|
||||
|
||||
@@ -225,31 +104,11 @@ serve(async (req) => {
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
subscriberId: subscriber.data._id,
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json', 'X-Request-ID': tracking.requestId },
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Error creating Novu subscriber', {
|
||||
error: formatEdgeError(error),
|
||||
requestId: tracking.requestId,
|
||||
duration
|
||||
});
|
||||
|
||||
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: 500,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user