-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSupabaseConnector.ts
More file actions
185 lines (160 loc) · 4.82 KB
/
SupabaseConnector.ts
File metadata and controls
185 lines (160 loc) · 4.82 KB
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
import {
AbstractPowerSyncDatabase,
BaseObserver,
CrudEntry,
type PowerSyncBackendConnector,
UpdateType,
type PowerSyncCredentials,
} from "@powersync/node";
import {
type Session,
type SupabaseClient,
createClient,
} from "@supabase/supabase-js";
export type SupabaseConfig = {
supabaseUrl: string;
supabaseAnonKey: string;
powersyncUrl: string;
};
/// Postgres Response codes that we cannot recover from by retrying.
const FATAL_RESPONSE_CODES = [
// Class 22 — Data Exception
// Examples include data type mismatch.
new RegExp("^22...$"),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
new RegExp("^23...$"),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
new RegExp("^42501$"),
];
export type SupabaseConnectorListener = {
initialized: () => void;
sessionStarted: (session: Session) => void;
};
export class SupabaseConnector
extends BaseObserver<SupabaseConnectorListener>
implements PowerSyncBackendConnector
{
readonly client: SupabaseClient;
readonly config: SupabaseConfig;
ready: boolean;
currentSession: Session | null;
constructor() {
super();
this.config = {
supabaseUrl: process.env.SUPABASE_URL!,
powersyncUrl: process.env.POWERSYNC_URL!,
supabaseAnonKey: process.env.SUPABASE_ANON_KEY!,
};
this.client = createClient(
this.config.supabaseUrl,
this.config.supabaseAnonKey,
{
auth: {
persistSession: true,
},
},
);
this.currentSession = null;
this.ready = false;
}
async init() {
if (this.ready) {
return;
}
const sessionResponse = await this.client.auth.getSession();
this.updateSession(sessionResponse.data.session);
this.ready = true;
this.iterateListeners((cb) => cb.initialized?.());
}
async login(username: string, password: string) {
const {
data: { session },
error,
} = await this.client.auth.signInWithPassword({
email: username,
password: password,
});
if (error) {
throw error;
}
this.updateSession(session);
}
async fetchCredentials() {
console.log("fetching credentials");
const {
data: { session },
error,
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
console.debug("session expires at", session.expires_at);
return {
endpoint: this.config.powersyncUrl,
token: session.access_token ?? "",
} satisfies PowerSyncCredentials;
}
async uploadData(database: AbstractPowerSyncDatabase): Promise<void> {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let lastOp: CrudEntry | null = null;
try {
// Note: If transactional consistency is important, use database functions
// or edge functions to process the entire transaction in a single call.
for (const op of transaction.crud) {
lastOp = op;
const table = this.client.from(op.table);
let result: any;
switch (op.op) {
case UpdateType.PUT:
const record = { ...op.opData, id: op.id };
result = await table.upsert(record);
break;
case UpdateType.PATCH:
result = await table.update(op.opData).eq("id", op.id);
break;
case UpdateType.DELETE:
result = await table.delete().eq("id", op.id);
break;
}
if (result.error) {
console.error(result.error);
result.error.message = `Could not update Supabase. Received error: ${result.error.message}`;
throw result.error;
}
}
await transaction.complete();
} catch (ex: any) {
console.debug(ex);
if (
typeof ex.code == "string" &&
FATAL_RESPONSE_CODES.some((regex) => regex.test(ex.code))
) {
/**
* Instead of blocking the queue with these errors,
* discard the (rest of the) transaction.
*
* Note that these errors typically indicate a bug in the application.
* If protecting against data loss is important, save the failing records
* elsewhere instead of discarding, and/or notify the user.
*/
console.error("Data upload error - discarding:", lastOp, ex);
await transaction.complete();
} else {
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
throw ex;
}
}
}
updateSession(session: Session | null) {
this.currentSession = session;
if (!session) {
return;
}
this.iterateListeners((cb) => cb.sessionStarted?.(session));
}
}