-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathstackrender-connector.ts
More file actions
131 lines (103 loc) · 3.79 KB
/
stackrender-connector.ts
File metadata and controls
131 lines (103 loc) · 3.79 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
import { v4 as uuid } from 'uuid';
import { AbstractPowerSyncDatabase, PowerSyncBackendConnector, UpdateType } from '@powersync/web';
export type DemoConfig = {
backendUrl: string;
powersyncUrl: string;
};
enum CheckpointMode {
CUSTOM = 'custom',
MANAGED = 'managed'
}
const USER_ID_STORAGE_KEY = 'ps_user_id';
export class StackRenderConnector implements PowerSyncBackendConnector {
readonly config: DemoConfig;
readonly userId: string;
private _clientId: string | null;
constructor() {
let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
if (!userId) {
userId = uuid();
localStorage.setItem(USER_ID_STORAGE_KEY, userId);
}
this.userId = userId;
this._clientId = null;
this.config = {
backendUrl: import.meta.env.VITE_BACKEND_URL as string,
powersyncUrl: import.meta.env.VITE_POWERSYNC_URL as string
};
}
async fetchCredentials() {
const tokenEndpoint = 'api/auth/token';
const res = await fetch(`${this.config.backendUrl}/${tokenEndpoint}?user_id=${this.userId}`);
if (!res.ok) {
throw new Error(`Received ${res.status} from ${tokenEndpoint}: ${await res.text()}`);
}
const body = await res.json();
return {
endpoint: this.config.powersyncUrl,
token: body.token
};
}
async uploadData(database: AbstractPowerSyncDatabase): Promise<void> {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
if (!this._clientId) {
this._clientId = await database.getClientId();
}
try {
let batch: any[] = [];
for (let operation of transaction.crud) {
if (operation.op != UpdateType.DELETE && Object.keys(operation.opData as any).length == 0)
continue
let payload = {
op: operation.op,
table: operation.table,
id: operation.id,
data: operation.opData
};
batch.push(payload);
}
if (batch.length > 0) {
const response = await fetch(`${this.config.backendUrl}/api/data`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ batch })
});
if (!response.ok) {
throw new Error(`Received ${response.status} from /api/data: ${await response.text()}`);
}
}
await transaction.complete(
import.meta.env.VITE_CHECKPOINT_MODE == CheckpointMode.CUSTOM
? await this.getCheckpoint(this._clientId)
: undefined
);
localStorage.setItem("last_upload_at", new Date().toISOString());
window.dispatchEvent(new StorageEvent("storage", { key: "lastUploadAt" }));
} catch (ex: any) {
throw ex;
}
}
/**
* Gets a custom Write Checkpoint from the backend. This is only used
* when custom Write Checkpoints are enabled during build.
*/
async getCheckpoint(client_id: string) {
const r = await fetch(`${this.config.backendUrl}/api/data/checkpoint`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
user_id: this.userId,
client_id: client_id
})
});
const j = await r.json();
return j.checkpoint as string;
}
}