All files / src/common/api supabaseClient.ts

62.44% Statements 143/229
59.45% Branches 22/37
77.77% Functions 7/9
62.44% Lines 143/229

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 2801x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x     1x 1x   1x                                                 1x 1x 1x 1x 1x     1x 1x 71x 71x 71x 71x 71x 71x 71x 71x 1x     1x 71x         71x 71x           71x 71x 71x     71x 65x 65x             65x             65x             65x             65x 65x 65x 65x 65x 65x 65x 65x 65x     8x                   6x 12x 12x 12x 12x 12x 12x   12x     6x 6x 6x 71x                   6x 6x   71x 71x     1x 114x 114x 114x 114x 114x 114x 85x 114x 29x 29x 114x   1x                           1x 114x 86x               85x 85x     1x                   1x 153x 153x 153x 153x   153x 153x 153x 153x 153x   153x 153x 88x   88x 88x 88x 88x 88x 88x 88x 88x 88x   88x 151x 65x   65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x   65x 65x 153x     1x  
import { AuthError, createClient, SupabaseClient } from "@supabase/supabase-js";
import { logger } from "../utils/logger";
 
// Configuration constants
const SUPABASE_CONFIG = {
  auth: {
    persistSession: true,
    autoRefreshToken: true,
    detectSessionInUrl: true,
    flowType: "pkce" as const,
  },
  global: {
    headers: {
      "X-Client-Info": "newsletter-hub-web",
    },
  },
  db: {
    schema: "public",
  },
  realtime: {
    params: {
      eventsPerSecond: 10,
    },
  },
} as const;
 
// Initialize logger
const log = logger;
 
// Environment variables validation
const supabaseUrl = (import.meta as any).env?.VITE_SUPABASE_URL || "";
const supabaseAnonKey = (import.meta as any).env?.VITE_SUPABASE_ANON_KEY || "";
 
if (!supabaseUrl || !supabaseAnonKey) {
  const missingVars = [];
  if (!supabaseUrl) missingVars.push("VITE_SUPABASE_URL");
  if (!supabaseAnonKey) missingVars.push("VITE_SUPABASE_ANON_KEY");
 
  log.error(
    `Missing required Supabase environment variables: ${missingVars.join(", ")}`,
    {
      component: "SupabaseClient",
      metadata: {
        missingVars,
        mode: "meta.env.MODE",
      },
    },
  );
 
  if (process.env.NODE_ENV === "development") {
    log.warn(
      "Running in development mode with missing Supabase configuration",
      { component: "SupabaseClient" },
    );
  }
}
 
// Create the Supabase client
export const supabase: SupabaseClient = createClient(
  supabaseUrl,
  supabaseAnonKey,
  SUPABASE_CONFIG,
);
 
// Enhanced error handling utilities
export class SupabaseError extends Error {
  constructor(
    message: string,
    public code?: string,
    public details?: unknown,
    public hint?: string,
  ) {
    super(message);
    this.name = "SupabaseError";
  }
}
 
// Error handler utility
export const handleSupabaseError = (error: unknown): never => {
  if (!error) {
    throw new SupabaseError("Unknown error occurred");
  }
 
  // Type guard for error objects with code property
  const hasCode = (
    err: unknown,
  ): err is {
    code: string;
    message?: string;
    details?: unknown;
    hint?: string;
  } => {
    return typeof err === "object" && err !== null && "code" in err;
  };
 
  // Handle different types of errors
  if (hasCode(error)) {
    switch (error.code) {
      case "PGRST116":
        throw new SupabaseError(
          "No data found",
          error.code,
          error.details,
          "The requested resource does not exist or you do not have permission to access it",
        );
      case "23505":
        throw new SupabaseError(
          "Duplicate entry",
          error.code,
          error.details,
          "A record with this information already exists",
        );
      case "23503":
        throw new SupabaseError(
          "Foreign key constraint violation",
          error.code,
          error.details,
          "Referenced record does not exist",
        );
      case "42501":
        throw new SupabaseError(
          "Insufficient privileges",
          error.code,
          error.details,
          "You do not have permission to perform this action",
        );
      default:
        throw new SupabaseError(
          error.message || "Database error occurred",
          error.code,
          error.details,
          error.hint,
        );
    }
  }
 
  // Handle auth errors
  if (error instanceof AuthError) {
    throw new SupabaseError(
      error.message,
      "AUTH_ERROR",
      error,
      "Authentication required or invalid credentials",
    );
  }
 
  // Type guard for error objects with name/message properties
  const hasNameOrMessage = (
    err: unknown,
  ): err is { name?: string; message?: string } => {
    return (
      typeof err === "object" &&
      err !== null &&
      ("name" in err || "message" in err)
    );
  };
 
  // Handle network errors
  if (
    hasNameOrMessage(error) &&
    (error.name === "NetworkError" || error.message?.includes("fetch"))
  ) {
    throw new SupabaseError(
      "Network error occurred",
      "NETWORK_ERROR",
      error,
      "Please check your internet connection and try again",
    );
  }
 
  // Generic error handling
  const errorMessage = hasNameOrMessage(error)
    ? error.message || "An unexpected error occurred"
    : "An unexpected error occurred";
  throw new SupabaseError(errorMessage, "UNKNOWN_ERROR", error);
};
 
// Auth state management utilities
export const getCurrentUser = async () => {
  try {
    const {
      data: { user },
      error,
    } = await supabase.auth.getUser();
    if (error) handleSupabaseError(error);
    return user;
  } catch (error) {
    handleSupabaseError(error);
  }
};
 
export const getCurrentSession = async () => {
  try {
    const {
      data: { session },
      error,
    } = await supabase.auth.getSession();
    if (error) handleSupabaseError(error);
    return session;
  } catch (error) {
    handleSupabaseError(error);
  }
};
 
// Utility to ensure user is authenticated
export const requireAuth = async () => {
  const user = await getCurrentUser();
  if (!user) {
    throw new SupabaseError(
      "User not authenticated",
      "AUTH_REQUIRED",
      null,
      "Please sign in to continue",
    );
  }
  return user;
};
 
// Connection health check
export const checkConnection = async (): Promise<boolean> => {
  try {
    const { error } = await supabase.from("users").select("id").limit(1);
    return !error;
  } catch {
    return false;
  }
};
 
// Performance monitoring
export const withPerformanceLogging = async <T>(
  operation: string,
  fn: () => Promise<T>,
): Promise<T> => {
  const start = performance.now();
 
  log.debug(`Starting operation: ${operation}`, {
    component: "SupabaseClient",
    action: "performance_start",
    metadata: { operation },
  });
 
  try {
    const result = await fn();
    const duration = performance.now() - start;
 
    log.info(`Operation completed: ${operation}`, {
      component: "SupabaseClient",
      action: "performance_success",
      metadata: {
        operation,
        duration: `${duration.toFixed(2)}ms`,
        durationMs: duration,
      },
    });
 
    return result;
  } catch (error) {
    const duration = performance.now() - start;
 
    log.error(
      `Operation failed: ${operation}`,
      {
        component: "SupabaseClient",
        action: "performance_error",
        metadata: {
          operation,
          duration: `${duration.toFixed(2)}ms`,
          durationMs: duration,
        },
      },
      error instanceof Error ? error : new Error(String(error)),
    );
 
    throw error;
  }
};
 
// Export the client as default for backward compatibility
export default supabase;