-
-
Notifications
You must be signed in to change notification settings - Fork 234
/
SupabaseClient.ts
190 lines (172 loc) · 6.14 KB
/
SupabaseClient.ts
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
import { DEFAULT_HEADERS } from './lib/constants'
import { SupabaseClientOptions } from './lib/types'
import { SupabaseAuthClient } from './lib/SupabaseAuthClient'
import { SupabaseQueryBuilder } from './lib/SupabaseQueryBuilder'
import { SupabaseStorageClient } from './lib/SupabaseStorageClient'
import { PostgrestClient } from '@supabase/postgrest-js'
import { RealtimeClient, RealtimeSubscription } from '@supabase/realtime-js'
const DEFAULT_OPTIONS = {
schema: 'public',
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
localStorage: globalThis.localStorage,
headers: DEFAULT_HEADERS,
}
/**
* Supabase Client.
*
* An isomorphic Javascript client for interacting with Postgres.
*/
export default class SupabaseClient {
/**
* Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies.
*/
auth: SupabaseAuthClient
/**
* Supabase Storage allows you to manage user-generated content, such as photos or videos.
*/
storage: SupabaseStorageClient
protected schema: string
protected restUrl: string
protected realtimeUrl: string
protected authUrl: string
protected storageUrl: string
protected realtime: RealtimeClient
/**
* Create a new client for use in the browser.
* @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.
* @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.
* @param options.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.
* @param options.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring.
* @param options.persistSession Set to "true" if you want to automatically save the user session into local storage.
* @param options.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user.
* @param options.headers Any additional headers to send with each network request.
*/
constructor(
protected supabaseUrl: string,
protected supabaseKey: string,
options?: SupabaseClientOptions
) {
if (!supabaseUrl) throw new Error('supabaseUrl is required.')
if (!supabaseKey) throw new Error('supabaseKey is required.')
const settings = { ...DEFAULT_OPTIONS, ...options }
this.restUrl = `${supabaseUrl}/rest/v1`
this.realtimeUrl = `${supabaseUrl}/realtime/v1`.replace('http', 'ws')
this.authUrl = `${supabaseUrl}/auth/v1`
this.storageUrl = `${supabaseUrl}/storage/v1`
this.schema = settings.schema
this.auth = this._initSupabaseAuthClient(settings)
this.realtime = this._initRealtimeClient()
this.storage = this._initStorageClient()
// In the future we might allow the user to pass in a logger to receive these events.
// this.realtime.onOpen(() => console.log('OPEN'))
// this.realtime.onClose(() => console.log('CLOSED'))
// this.realtime.onError((e: Error) => console.log('Socket error', e))
}
/**
* Perform a table operation.
*
* @param table The table name to operate on.
*/
from<T = any>(table: string): SupabaseQueryBuilder<T> {
const url = `${this.restUrl}/${table}`
return new SupabaseQueryBuilder<T>(url, {
headers: this._getAuthHeaders(),
schema: this.schema,
realtime: this.realtime,
table,
})
}
/**
* Perform a stored procedure call.
*
* @param fn The function name to call.
* @param params The parameters to pass to the function call.
*/
rpc<T = any>(fn: string, params?: object) {
const rest = this._initPostgRESTClient()
return rest.rpc<T>(fn, params)
}
/**
* Removes an active subscription and returns the number of open connections.
*
* @param subscription The subscription you want to remove.
*/
removeSubscription(subscription: RealtimeSubscription) {
return new Promise(async (resolve) => {
try {
await this._closeSubscription(subscription)
const openSubscriptions = this.getSubscriptions().length
if (!openSubscriptions) {
const { error } = await this.realtime.disconnect()
if (error) return resolve({ error })
}
return resolve({ error: null, data: { openSubscriptions } })
} catch (error) {
return resolve({ error })
}
})
}
private async _closeSubscription(subscription: RealtimeSubscription) {
if (!subscription.isClosed()) {
await this._closeChannel(subscription)
}
}
/**
* Returns an array of all your subscriptions.
*/
getSubscriptions(): RealtimeSubscription[] {
return this.realtime.channels
}
private _initSupabaseAuthClient({
autoRefreshToken,
persistSession,
detectSessionInUrl,
localStorage,
}: SupabaseClientOptions) {
return new SupabaseAuthClient({
url: this.authUrl,
headers: {
Authorization: `Bearer ${this.supabaseKey}`,
apikey: `${this.supabaseKey}`,
},
autoRefreshToken,
persistSession,
detectSessionInUrl,
localStorage,
})
}
private _initRealtimeClient() {
return new RealtimeClient(this.realtimeUrl, {
params: { apikey: this.supabaseKey },
})
}
private _initPostgRESTClient() {
return new PostgrestClient(this.restUrl, {
headers: this._getAuthHeaders(),
schema: this.schema,
})
}
private _initStorageClient() {
return new SupabaseStorageClient(this.storageUrl, this._getAuthHeaders())
}
private _getAuthHeaders(): { [key: string]: string } {
const headers: { [key: string]: string } = {}
const authBearer = this.auth.session()?.access_token ?? this.supabaseKey
headers['apikey'] = this.supabaseKey
headers['Authorization'] = `Bearer ${authBearer}`
return headers
}
private _closeChannel(subscription: RealtimeSubscription) {
return new Promise((resolve, reject) => {
subscription
.unsubscribe()
.receive('ok', () => {
this.realtime.remove(subscription)
return resolve(true)
})
.receive('error', (e: Error) => reject(e))
})
}
}