forked from supabase-community/supabase-csharp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClient.cs
283 lines (244 loc) · 10.6 KB
/
Client.cs
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Supabase.Postgrest.Interfaces;
using Supabase.Postgrest.Models;
using Supabase.Postgrest.Responses;
using Supabase.Core;
using Supabase.Functions.Interfaces;
using Supabase.Gotrue;
using Supabase.Gotrue.Interfaces;
using Supabase.Interfaces;
using Supabase.Realtime;
using Supabase.Realtime.Interfaces;
using Supabase.Storage;
using Supabase.Storage.Interfaces;
using static Supabase.Gotrue.Constants;
namespace Supabase
{
/// <summary>
/// A singleton class representing a Supabase Client.
/// </summary>
public class Client : ISupabaseClient<User, Session, RealtimeSocket, RealtimeChannel, Bucket, FileObject>
{
/// <summary>
/// Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies.
/// </summary>
public IGotrueClient<User, Session> Auth
{
get => _auth;
set
{
// Remove existing internal state listener (if applicable)
_auth.RemoveStateChangedListener(Auth_StateChanged);
_auth = value;
_auth.AddStateChangedListener(Auth_StateChanged);
}
}
private IGotrueClient<User, Session> _auth;
/// <summary>
/// Returns a Stateless Gotrue Admin client given a service_key JWT. This should really only be accessed from a
/// server environment where a private service_key would remain secure.
/// </summary>
/// <param name="serviceKey"></param>
/// <returns></returns>
public IGotrueAdminClient<User> AdminAuth(string serviceKey) =>
new AdminClient(serviceKey, new Gotrue.ClientOptions
{
Url = string.Format(_options.AuthUrlFormat, _supabaseUrl),
AutoRefreshToken = _options.AutoRefreshToken
})
{
GetHeaders = GetAuthHeaders,
};
/// <summary>
/// Supabase Realtime allows for realtime feedback on database changes.
/// </summary>
public IRealtimeClient<RealtimeSocket, RealtimeChannel> Realtime
{
get => _realtime;
set
{
// Disconnect from previous RealtimeSocket (if applicable)
_realtime.Disconnect();
_realtime = value;
}
}
private IRealtimeClient<RealtimeSocket, RealtimeChannel> _realtime;
/// <summary>
/// Supabase Edge functions allow you to deploy and invoke edge functions.
/// </summary>
public IFunctionsClient Functions
{
get => _functions;
set => _functions = value;
}
private IFunctionsClient _functions;
/// <summary>
/// Supabase Postgrest allows for strongly typed REST interactions with the your database.
/// </summary>
public IPostgrestClient Postgrest
{
get => _postgrest;
set => _postgrest = value;
}
private IPostgrestClient _postgrest;
/// <summary>
/// Supabase Storage allows you to manage user-generated content, such as photos or videos.
/// </summary>
public IStorageClient<Bucket, FileObject> Storage
{
get => _storage;
set => _storage = value;
}
private IStorageClient<Bucket, FileObject> _storage;
private readonly string? _supabaseUrl;
private readonly string? _supabaseKey;
private readonly SupabaseOptions _options;
/// <summary>
/// Constructor supplied for dependency injection support.
/// </summary>
/// <param name="auth"></param>
/// <param name="realtime"></param>
/// <param name="functions"></param>
/// <param name="postgrest"></param>
/// <param name="storage"></param>
/// <param name="options"></param>
public Client(IGotrueClient<User, Session> auth, IRealtimeClient<RealtimeSocket, RealtimeChannel> realtime,
IFunctionsClient functions, IPostgrestClient postgrest, IStorageClient<Bucket, FileObject> storage,
SupabaseOptions options)
{
_auth = auth;
_realtime = realtime;
_functions = functions;
_postgrest = postgrest;
_storage = storage;
_options = options;
}
/// <summary>
/// Creates a new Supabase Client.
/// </summary>
/// <param name="supabaseUrl"></param>
/// <param name="supabaseKey"></param>
/// <param name="options"></param>
public Client(string supabaseUrl, string? supabaseKey, SupabaseOptions? options = null)
{
_supabaseUrl = supabaseUrl;
_supabaseKey = supabaseKey;
_options = options ?? new SupabaseOptions();
var authUrl = string.Format(_options.AuthUrlFormat, supabaseUrl);
var restUrl = string.Format(_options.RestUrlFormat, supabaseUrl);
var realtimeUrl = string.Format(_options.RealtimeUrlFormat, supabaseUrl).Replace("http", "ws");
var storageUrl = string.Format(_options.StorageUrlFormat, supabaseUrl);
var schema = _options.Schema;
// See: https://github.com/supabase/supabase-js/blob/09065a65f171bc28a9fd7b831af2c24e5f1a380b/src/SupabaseClient.ts#L77-L83
var isPlatform = new Regex(@"(supabase\.co)|(supabase\.in)").Match(supabaseUrl);
string? functionsUrl;
if (isPlatform.Success)
{
var parts = supabaseUrl.Split('.');
functionsUrl = $"{parts[0]}.functions.{parts[1]}.{parts[2]}";
}
else
{
functionsUrl = string.Format(_options.FunctionsUrlFormat, supabaseUrl);
}
// Init Auth
var gotrueOptions = new Gotrue.ClientOptions
{
Url = authUrl,
AutoRefreshToken = _options.AutoRefreshToken
};
_auth = new Gotrue.Client(gotrueOptions);
_auth.SetPersistence(_options.SessionHandler);
_auth.AddStateChangedListener(Auth_StateChanged);
_auth.GetHeaders = GetAuthHeaders;
// Init Realtime
var realtimeOptions = new Realtime.ClientOptions
{
Parameters = { ApiKey = _supabaseKey }
};
_realtime = new Realtime.Client(realtimeUrl, realtimeOptions);
_postgrest = new Postgrest.Client(restUrl, new Postgrest.ClientOptions { Schema = schema });
_postgrest.GetHeaders = GetAuthHeaders;
_functions = new Functions.Client(functionsUrl);
_functions.GetHeaders = GetAuthHeaders;
_storage = new Storage.Client(storageUrl, _options.StorageClientOptions);
_storage.GetHeaders = GetAuthHeaders;
}
/// <summary>
/// Attempts to retrieve the session from Gotrue (set in <see cref="SupabaseOptions"/>) and connects to realtime (if `options.AutoConnectRealtime` is set)
/// </summary>
public async Task<ISupabaseClient<User, Session, RealtimeSocket, RealtimeChannel, Bucket, FileObject>>
InitializeAsync()
{
await Auth.RetrieveSessionAsync();
if (_options.AutoConnectRealtime)
await Realtime.ConnectAsync();
return this;
}
private void Auth_StateChanged(object sender, AuthState e)
{
switch (e)
{
// Pass new Auth down to Realtime
// Ref: https://github.com/supabase-community/supabase-csharp/issues/12
case AuthState.SignedIn:
case AuthState.TokenRefreshed:
case AuthState.UserUpdated:
if (Auth.CurrentSession?.AccessToken != null)
Realtime.SetAuth(Auth.CurrentSession.AccessToken);
break;
// Remove Realtime Subscriptions on Auth Sign-out.
case AuthState.SignedOut:
if (Realtime.Subscriptions.Values != null)
foreach (var subscription in Realtime.Subscriptions.Values)
subscription.Unsubscribe();
break;
case AuthState.PasswordRecovery: break;
case AuthState.Shutdown: break;
default: throw new ArgumentOutOfRangeException(nameof(e), e, null);
}
}
/// <summary>
/// Gets the Postgrest client to prepare for a query.
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <returns></returns>
public ISupabaseTable<TModel, RealtimeChannel> From<TModel>() where TModel : BaseModel, new() =>
new SupabaseTable<TModel>(Postgrest, Realtime);
/// <inheritdoc />
public Task<BaseResponse> Rpc(string procedureName, object? parameters) =>
_postgrest.Rpc(procedureName, parameters);
/// <inheritdoc />
public Task<TModeledResponse?> Rpc<TModeledResponse>(string procedureName, object? parameters) =>
_postgrest.Rpc<TModeledResponse>(procedureName, parameters);
/// <summary>
/// Produces dictionary of Headers that will be supplied to child clients.
///</summary>
internal Dictionary<string, string> GetAuthHeaders()
{
var headers = new Dictionary<string, string>
{
["X-Client-Info"] = Util.GetAssemblyVersion(typeof(Client))
};
if (_supabaseKey != null)
headers["apiKey"] = _supabaseKey;
// In Regard To: https://github.com/supabase/supabase-csharp/issues/5
if (_options.Headers.TryGetValue("Authorization", out var header))
{
headers["Authorization"] = header;
}
else
{
var bearer = Auth.CurrentSession?.AccessToken ?? _supabaseKey;
headers["Authorization"] = $"Bearer {bearer}";
}
// Add supplied headers from `ClientOptions` by developer
foreach (var kvp in _options.Headers)
headers[kvp.Key] = kvp.Value;
return headers;
}
}
}