Skip to content

Instantly share code, notes, and snippets.

@ftonato
Created February 7, 2021 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftonato/23585d6098490d0239feaeddb7f1e56c to your computer and use it in GitHub Desktop.
Save ftonato/23585d6098490d0239feaeddb7f1e56c to your computer and use it in GitHub Desktop.
SupabaseService using Singleton pattern
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()
})()
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