• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

supabase / supabase-js / 5089128794

26 May 2023 09:05AM UTC coverage: 67.513%. Remained the same
5089128794

push

github

Bobbie Soedirgo
feat(deps): bump postgrest-js to 1.7.0

46 of 86 branches covered (53.49%)

Branch coverage included in aggregate %.

87 of 111 relevant lines covered (78.38%)

4.09 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

67.19
/src/SupabaseClient.ts
1
import { FunctionsClient } from '@supabase/functions-js'
2✔
2
import { AuthChangeEvent } from '@supabase/gotrue-js'
3
import {
2✔
4
  PostgrestClient,
5
  PostgrestFilterBuilder,
6
  PostgrestQueryBuilder,
7
} from '@supabase/postgrest-js'
8
import {
2✔
9
  RealtimeChannel,
10
  RealtimeChannelOptions,
11
  RealtimeClient,
12
  RealtimeClientOptions,
13
} from '@supabase/realtime-js'
14
import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'
2✔
15
import { DEFAULT_HEADERS } from './lib/constants'
2✔
16
import { fetchWithAuth } from './lib/fetch'
2✔
17
import { stripTrailingSlash, applySettingDefaults } from './lib/helpers'
2✔
18
import { SupabaseAuthClient } from './lib/SupabaseAuthClient'
2✔
19
import { Fetch, GenericSchema, SupabaseClientOptions, SupabaseAuthClientOptions } from './lib/types'
20

21
const DEFAULT_GLOBAL_OPTIONS = {
2✔
22
  headers: DEFAULT_HEADERS,
23
}
24

25
const DEFAULT_DB_OPTIONS = {
2✔
26
  schema: 'public',
27
}
28

29
const DEFAULT_AUTH_OPTIONS: SupabaseAuthClientOptions = {
2✔
30
  autoRefreshToken: true,
31
  persistSession: true,
32
  detectSessionInUrl: true,
33
  flowType: 'implicit',
34
}
35

36
const DEFAULT_REALTIME_OPTIONS: RealtimeClientOptions = {}
2✔
37

38
/**
39
 * Supabase Client.
40
 *
41
 * An isomorphic Javascript client for interacting with Postgres.
42
 */
43
export default class SupabaseClient<
2✔
44
  Database = any,
45
  SchemaName extends string & keyof Database = 'public' extends keyof Database
46
    ? 'public'
47
    : string & keyof Database,
48
  Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
49
    ? Database[SchemaName]
50
    : any
51
> {
52
  /**
53
   * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies.
54
   */
55
  auth: SupabaseAuthClient
56
  realtime: RealtimeClient
57

58
  protected realtimeUrl: string
59
  protected authUrl: string
60
  protected storageUrl: string
61
  protected functionsUrl: string
62
  protected rest: PostgrestClient<Database, SchemaName>
63
  protected storageKey: string
64
  protected fetch?: Fetch
65
  protected changedAccessToken: string | undefined
66

67
  protected headers: {
68
    [key: string]: string
69
  }
70

71
  /**
72
   * Create a new client for use in the browser.
73
   * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.
74
   * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.
75
   * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.
76
   * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring.
77
   * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage.
78
   * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user.
79
   * @param options.realtime Options passed along to realtime-js constructor.
80
   * @param options.global.fetch A custom fetch implementation.
81
   * @param options.global.headers Any additional headers to send with each network request.
82
   */
83
  constructor(
84
    protected supabaseUrl: string,
8✔
85
    protected supabaseKey: string,
8✔
86
    options?: SupabaseClientOptions<SchemaName>
87
  ) {
88
    if (!supabaseUrl) throw new Error('supabaseUrl is required.')
8✔
89
    if (!supabaseKey) throw new Error('supabaseKey is required.')
7✔
90

91
    const _supabaseUrl = stripTrailingSlash(supabaseUrl)
6✔
92

93
    this.realtimeUrl = `${_supabaseUrl}/realtime/v1`.replace(/^http/i, 'ws')
6✔
94
    this.authUrl = `${_supabaseUrl}/auth/v1`
6✔
95
    this.storageUrl = `${_supabaseUrl}/storage/v1`
6✔
96

97
    const isPlatform = _supabaseUrl.match(/(supabase\.co)|(supabase\.in)/)
6✔
98
    if (isPlatform) {
6✔
99
      const urlParts = _supabaseUrl.split('.')
1✔
100
      this.functionsUrl = `${urlParts[0]}.functions.${urlParts[1]}.${urlParts[2]}`
1✔
101
    } else {
102
      this.functionsUrl = `${_supabaseUrl}/functions/v1`
5✔
103
    }
104
    // default storage key uses the supabase project ref as a namespace
105
    const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token`
6✔
106
    const DEFAULTS = {
6✔
107
      db: DEFAULT_DB_OPTIONS,
108
      realtime: DEFAULT_REALTIME_OPTIONS,
109
      auth: { ...DEFAULT_AUTH_OPTIONS, storageKey: defaultStorageKey },
110
      global: DEFAULT_GLOBAL_OPTIONS,
111
    }
112

113
    const settings = applySettingDefaults(options ?? {}, DEFAULTS)
6✔
114

115
    this.storageKey = settings.auth?.storageKey ?? ''
6!
116
    this.headers = settings.global?.headers ?? {}
6!
117

118
    this.auth = this._initSupabaseAuthClient(
6✔
119
      settings.auth ?? {},
18!
120
      this.headers,
121
      settings.global?.fetch
18!
122
    )
123
    this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global?.fetch)
6!
124

125
    this.realtime = this._initRealtimeClient({ headers: this.headers, ...settings.realtime })
6✔
126
    this.rest = new PostgrestClient(`${_supabaseUrl}/rest/v1`, {
6✔
127
      headers: this.headers,
128
      schema: settings.db?.schema,
18!
129
      fetch: this.fetch,
130
    })
131

132
    this._listenForAuthEvents()
6✔
133
  }
134

135
  /**
136
   * Supabase Functions allows you to deploy and invoke edge functions.
137
   */
138
  get functions() {
139
    return new FunctionsClient(this.functionsUrl, {
×
140
      headers: this.headers,
141
      customFetch: this.fetch,
142
    })
143
  }
144

145
  /**
146
   * Supabase Storage allows you to manage user-generated content, such as photos or videos.
147
   */
148
  get storage() {
149
    return new SupabaseStorageClient(this.storageUrl, this.headers, this.fetch)
×
150
  }
151

152
  from<
153
    TableName extends string & keyof Schema['Tables'],
154
    Table extends Schema['Tables'][TableName]
155
  >(relation: TableName): PostgrestQueryBuilder<Schema, Table>
156
  from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(
157
    relation: ViewName
158
  ): PostgrestQueryBuilder<Schema, View>
159
  from(relation: string): PostgrestQueryBuilder<Schema, any>
160
  /**
161
   * Perform a query on a table or a view.
162
   *
163
   * @param relation - The table or view name to query
164
   */
165
  from(relation: string): PostgrestQueryBuilder<Schema, any> {
166
    return this.rest.from(relation)
×
167
  }
168

169
  /**
170
   * Perform a function call.
171
   *
172
   * @param fn - The function name to call
173
   * @param args - The arguments to pass to the function call
174
   * @param options - Named parameters
175
   * @param options.head - When set to `true`, `data` will not be returned.
176
   * Useful if you only need the count.
177
   * @param options.count - Count algorithm to use to count rows returned by the
178
   * function. Only applicable for [set-returning
179
   * functions](https://www.postgresql.org/docs/current/functions-srf.html).
180
   *
181
   * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
182
   * hood.
183
   *
184
   * `"planned"`: Approximated but fast count algorithm. Uses the Postgres
185
   * statistics under the hood.
186
   *
187
   * `"estimated"`: Uses exact count for low numbers and planned count for high
188
   * numbers.
189
   */
190
  rpc<
191
    FunctionName extends string & keyof Schema['Functions'],
192
    Function_ extends Schema['Functions'][FunctionName]
193
  >(
194
    fn: FunctionName,
195
    args: Function_['Args'] = {},
1✔
196
    options?: {
197
      head?: boolean
198
      count?: 'exact' | 'planned' | 'estimated'
199
    }
200
  ): PostgrestFilterBuilder<
201
    Schema,
202
    Function_['Returns'] extends any[]
203
      ? Function_['Returns'][number] extends Record<string, unknown>
204
        ? Function_['Returns'][number]
205
        : never
206
      : never,
207
    Function_['Returns']
208
  > {
209
    return this.rest.rpc(fn, args, options)
1✔
210
  }
211

212
  /**
213
   * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.
214
   *
215
   * @param {string} name - The name of the Realtime channel.
216
   * @param {Object} opts - The options to pass to the Realtime channel.
217
   *
218
   */
219
  channel(name: string, opts: RealtimeChannelOptions = { config: {} }): RealtimeChannel {
×
220
    return this.realtime.channel(name, opts)
×
221
  }
222

223
  /**
224
   * Returns all Realtime channels.
225
   */
226
  getChannels(): RealtimeChannel[] {
227
    return this.realtime.getChannels()
×
228
  }
229

230
  /**
231
   * Unsubscribes and removes Realtime channel from Realtime client.
232
   *
233
   * @param {RealtimeChannel} channel - The name of the Realtime channel.
234
   *
235
   */
236
  removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'> {
237
    return this.realtime.removeChannel(channel)
×
238
  }
239

240
  /**
241
   * Unsubscribes and removes all Realtime channels from Realtime client.
242
   */
243
  removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]> {
244
    return this.realtime.removeAllChannels()
×
245
  }
246

247
  private async _getAccessToken() {
248
    const { data } = await this.auth.getSession()
×
249

250
    return data.session?.access_token ?? null
×
251
  }
252

253
  private _initSupabaseAuthClient(
254
    {
255
      autoRefreshToken,
256
      persistSession,
257
      detectSessionInUrl,
258
      storage,
259
      storageKey,
260
      flowType,
261
    }: SupabaseAuthClientOptions,
262
    headers?: Record<string, string>,
263
    fetch?: Fetch
264
  ) {
265
    const authHeaders = {
7✔
266
      Authorization: `Bearer ${this.supabaseKey}`,
267
      apikey: `${this.supabaseKey}`,
268
    }
269
    return new SupabaseAuthClient({
7✔
270
      url: this.authUrl,
271
      headers: { ...authHeaders, ...headers },
272
      storageKey: storageKey,
273
      autoRefreshToken,
274
      persistSession,
275
      detectSessionInUrl,
276
      storage,
277
      flowType,
278
      fetch,
279
    })
280
  }
281

282
  private _initRealtimeClient(options: RealtimeClientOptions) {
283
    return new RealtimeClient(this.realtimeUrl, {
6✔
284
      ...options,
285
      params: { ...{ apikey: this.supabaseKey }, ...options?.params },
18!
286
    })
287
  }
288

289
  private _listenForAuthEvents() {
290
    let data = this.auth.onAuthStateChange((event, session) => {
6✔
291
      this._handleTokenChanged(event, session?.access_token, 'CLIENT')
6!
292
    })
293
    return data
6✔
294
  }
295

296
  private _handleTokenChanged(
297
    event: AuthChangeEvent,
298
    token: string | undefined,
299
    source: 'CLIENT' | 'STORAGE'
300
  ) {
301
    if (
6!
302
      (event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') &&
12!
303
      this.changedAccessToken !== token
304
    ) {
305
      // Token has changed
306
      this.realtime.setAuth(token ?? null)
×
307

308
      this.changedAccessToken = token
×
309
    } else if (event === 'SIGNED_OUT') {
6!
310
      // Token is removed
311
      this.realtime.setAuth(this.supabaseKey)
×
312
      if (source == 'STORAGE') this.auth.signOut()
×
313
      this.changedAccessToken = undefined
×
314
    }
315
  }
316
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc