2024-04-21 10:36:48 -07:00
import { createClient , SupabaseClient } from "@supabase/supabase-js" ;
2024-11-07 20:57:33 +01:00
import { logger } from "../lib/logger" ;
2024-09-04 15:57:57 -03:00
import { configDotenv } from "dotenv" ;
configDotenv ( ) ;
2024-04-15 17:01:47 -04:00
2024-04-21 09:31:22 -07:00
// SupabaseService class initializes the Supabase client conditionally based on environment variables.
class SupabaseService {
private client : SupabaseClient | null = null ;
constructor ( ) {
const supabaseUrl = process . env . SUPABASE_URL ;
const supabaseServiceToken = process . env . SUPABASE_SERVICE_TOKEN ;
2024-12-11 19:46:11 -03:00
const useDbAuthentication = process . env . USE_DB_AUTHENTICATION === "true" ;
2024-04-21 09:31:22 -07:00
// Only initialize the Supabase client if both URL and Service Token are provided.
2024-08-12 14:20:41 -03:00
if ( ! useDbAuthentication ) {
2024-04-21 09:31:22 -07:00
// Warn the user that Authentication is disabled by setting the client to null
2024-11-07 20:57:33 +01:00
logger . warn (
2024-07-25 09:48:06 -03:00
"Authentication is disabled. Supabase client will not be initialized."
2024-04-21 10:36:48 -07:00
) ;
2024-04-21 09:31:22 -07:00
this . client = null ;
} else if ( ! supabaseUrl || ! supabaseServiceToken ) {
2024-11-07 20:57:33 +01:00
logger . error (
2024-07-25 09:48:06 -03:00
"Supabase environment variables aren't configured correctly. Supabase client will not be initialized. Fix ENV configuration or disable DB authentication with USE_DB_AUTHENTICATION env variable"
2024-04-21 10:36:48 -07:00
) ;
2024-04-21 09:31:22 -07:00
} else {
this . client = createClient ( supabaseUrl , supabaseServiceToken ) ;
}
}
// Provides access to the initialized Supabase client, if available.
getClient ( ) : SupabaseClient | null {
return this . client ;
}
}
// Using a Proxy to handle dynamic access to the Supabase client or service methods.
// This approach ensures that if Supabase is not configured, any attempt to use it will result in a clear error.
2024-04-21 10:36:48 -07:00
export const supabase_service : SupabaseClient = new Proxy (
new SupabaseService ( ) ,
{
get : function ( target , prop , receiver ) {
const client = target . getClient ( ) ;
// If the Supabase client is not initialized, intercept property access to provide meaningful error feedback.
if ( client === null ) {
return ( ) = > {
throw new Error ( "Supabase client is not configured." ) ;
} ;
}
// Direct access to SupabaseService properties takes precedence.
if ( prop in target ) {
return Reflect . get ( target , prop , receiver ) ;
}
// Otherwise, delegate access to the Supabase client.
return Reflect . get ( client , prop , receiver ) ;
2024-12-11 19:46:11 -03:00
}
2024-04-21 09:31:22 -07:00
}
2024-04-21 10:36:48 -07:00
) as unknown as SupabaseClient ;