-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
247 lines (225 loc) · 7.25 KB
/
index.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
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
import {
REALTIME_SUBSCRIBE_STATES,
RealtimeChannel,
RealtimePostgresChangesPayload,
SupabaseClient,
} from '@supabase/supabase-js';
type ID = string | number;
export type LiveRow = Record<string, unknown> & {
id: ID;
created_at: string;
updated_at: string | null;
};
export type LiveTableCallback<TableRow extends LiveRow> = (
err: Error | undefined,
records: readonly TableRow[],
) => void;
export type LiveTableParams<
TableRow extends LiveRow,
ColumnName extends keyof TableRow & string,
> = {
table: string;
filterColumn: ColumnName;
filterValue: TableRow[ColumnName];
callback: LiveTableCallback<TableRow>;
schema?: string;
channelName?: string;
};
export function liveTable<TableRow extends LiveRow>(
supabase: SupabaseClient,
params: LiveTableParams<TableRow, keyof TableRow & string>,
): RealtimeChannel {
const parseTimestamp = (timestamp: string) => new Date(timestamp).getTime();
const liveTable = new LiveTable<TableRow>(parseTimestamp);
const {
table,
filterColumn,
filterValue,
callback,
channelName = `${table}-${filterColumn}-${filterValue}`,
schema = 'public',
} = params;
return (
supabase
.channel(channelName)
.on(
'postgres_changes',
{
event: '*',
schema,
table,
filter: `${filterColumn}=eq.${filterValue}`,
},
(payload: RealtimePostgresChangesPayload<TableRow>) => {
const timestamp = payload.commit_timestamp;
switch (payload.eventType) {
case 'INSERT': {
liveTable.processEvent({ type: 'INSERT', record: payload.new, timestamp });
break;
}
case 'UPDATE': {
liveTable.processEvent({ type: 'UPDATE', record: payload.new, timestamp });
break;
}
case 'DELETE': {
liveTable.processEvent({ type: 'DELETE', record: payload.old, timestamp });
break;
}
}
callback(undefined, liveTable.records);
},
)
.subscribe((status) => {
const ERROR_STATES: `${REALTIME_SUBSCRIBE_STATES}`[] = [
REALTIME_SUBSCRIBE_STATES.TIMED_OUT,
REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR,
];
if (ERROR_STATES.includes(status)) {
callback(new Error(`SUBSCRIPTION: ${status}`), []);
}
})
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
.on('system', {}, (payload) => {
if (payload.extension === 'postgres_changes') {
supabase
.from(table)
.select('*')
.eq(filterColumn, filterValue)
.then(({ error, data }) => {
if (error) {
callback(new Error(error.message), []);
} else {
liveTable.processSnapshot(data);
callback(undefined, liveTable.records);
}
});
}
})
);
}
type Insert<TableRow extends LiveRow> = {
type: 'INSERT';
record: TableRow;
timestamp: string;
};
type Update<TableRow extends LiveRow> = {
type: 'UPDATE';
record: Partial<TableRow>;
timestamp: string;
};
type Delete<TableRow extends LiveRow> = {
type: 'DELETE';
record: Partial<TableRow>;
timestamp: string;
};
export type LiveTableEvent<TableRow extends LiveRow> =
| Insert<TableRow>
| Update<TableRow>
| Delete<TableRow>;
export type ILiveTable<TableRow extends LiveRow> = {
processSnapshot(records: readonly TableRow[]): void;
processEvent(event: LiveTableEvent<TableRow>): void;
readonly records: readonly TableRow[];
};
export type ParseTimestamp = (timestamp: string) => number;
export class LiveTable<TableRow extends LiveRow> implements ILiveTable<TableRow> {
private readonly recordById = new Map<ID, TableRow>();
private readonly bufferedEvents: LiveTableEvent<TableRow>[] = [];
private snapshotTimestamp: number | undefined;
constructor(private readonly parseTimestamp: ParseTimestamp) {}
public processEvent(event: LiveTableEvent<TableRow>) {
if (this.snapshotTimestamp === undefined) {
this.bufferedEvents.push(event);
return;
}
const eventTimestamp = this.parseTimestamp(event.timestamp);
if (eventTimestamp < this.snapshotTimestamp) {
// This event is older than the snapshot, so we can ignore it
return;
}
const { type, record } = validate(event);
switch (type) {
case 'INSERT': {
if (this.recordById.has(record.id)) {
const existing = this.recordById.get(record.id)!;
// If the timestamp of the existing record is the same as the event timestamp, we'll ignore this event
const recordTimestamp = this.parseTimestamp(record.updated_at || record.created_at);
const existingTimestamp = this.parseTimestamp(
existing?.updated_at || existing?.created_at,
);
if (recordTimestamp === existingTimestamp) {
return;
}
throw new Error(
`Conflicting insert. We already have ${JSON.stringify(
existing,
)} from a snapshot. Cannot insert ${JSON.stringify(record)}`,
);
}
this.recordById.set(record.id, record);
break;
}
case 'UPDATE': {
const id = record.id;
if (!id) {
throw new Error(`Cannot update. Record has no id: ${JSON.stringify(record)}`);
}
const oldRecord = this.recordById.get(id);
if (oldRecord === undefined) {
throw new Error(`Cannot update. Record does not exist: ${JSON.stringify(record)}`);
}
this.recordById.set(id, { ...oldRecord, ...record });
break;
}
case 'DELETE': {
const id = record.id;
if (!id) {
throw new Error(`Cannot delete. Record has no id: ${JSON.stringify(record)}`);
}
this.recordById.delete(id);
break;
}
}
}
processSnapshot(records: readonly TableRow[]) {
this.snapshotTimestamp = 0;
for (const record of records) {
const recordTimestamp = this.parseTimestamp(record.updated_at || record.created_at);
if (recordTimestamp > this.snapshotTimestamp) {
this.snapshotTimestamp = recordTimestamp;
}
this.recordById.set(record.id, record);
}
for (const event of this.bufferedEvents) {
this.processEvent(event);
}
}
/**
* Returns the replica of the table as an array of records.
* The records are not sorted, and there is no guarantee of order.
*/
get records(): readonly TableRow[] {
return [...this.recordById.values()];
}
}
function validate<TableRow extends LiveRow>(
event: LiveTableEvent<TableRow>,
): LiveTableEvent<TableRow> {
const { timestamp, record, type } = event;
const eventTimestamp = new Date(timestamp);
if (type === 'DELETE') {
// Delete events don't have timestamps on the record - just the id
return event;
}
if (!record.created_at) {
throw new Error(`Record has no created_at. Event: ${JSON.stringify(event)}`);
}
const recordTimestamp = new Date(record.updated_at || record.created_at);
if (eventTimestamp < recordTimestamp) {
throw new Error(
`Event timestamp ${timestamp} is older than record timestamp ${recordTimestamp}`,
);
}
return event;
}