Created
February 7, 2021 15:25
-
-
Save ftonato/23585d6098490d0239feaeddb7f1e56c to your computer and use it in GitHub Desktop.
SupabaseService using Singleton pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SupabaseService from 'Supabase.service.js' | |
const supabaseUrl = 'Your app URL here' | |
const supabaseKey = 'Your app Key here' | |
// Instantiate | |
const supabase_instance = new SupabaseService(supabaseUrl, supabaseKey) | |
console.log('instance: ', supabase_instance) // Return the unique instance for the class | |
// Reinstantiate attempt | |
setTimeout(() => { | |
const supabase_reinstance_attempt = new SupabaseService() | |
console.log('reinstance attempt: ', supabase_reinstance_attempt) // Return the same instance (the first one) | |
}, 1000) | |
// ---- --- ---- // | |
// --- Usage --- // | |
// ---- --- ---- // | |
(async () => { | |
const { data, error } = await supabase_instance.supabase | |
.from('table') | |
.select() | |
})() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createClient } from '@supabase/supabase-js' | |
let instance = null | |
export default class SupabaseService { | |
constructor(supabaseUrl = process.env.SUPABASE_URL, supabaseKey = process.env.SUPABASE_SECRET_KEY) { | |
if (!supabaseUrl) throw new Error(`${SupabaseService.getClassName()} => supabaseUrl is required.`) | |
if (!supabaseKey) throw new Error(`${SupabaseService.getClassName()} => supabaseKey is required.`) | |
if (!instance) { | |
instance = this | |
} | |
this.supabase = createClient(supabaseUrl, supabaseKey) | |
return instance | |
} | |
static getClassName() { | |
return SupabaseService.name | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment