|
| 1 | +import { AbstractPowerSyncDatabase, column, PowerSyncBackendConnector, Schema, Table } from '@powersync/node'; |
| 2 | + |
| 3 | +export class DemoConnector implements PowerSyncBackendConnector { |
| 4 | + async fetchCredentials() { |
| 5 | + const response = await fetch(`${process.env.BACKEND}/api/auth/token`); |
| 6 | + if (response.status != 200) { |
| 7 | + throw 'Could not fetch token'; |
| 8 | + } |
| 9 | + |
| 10 | + const { token } = await response.json(); |
| 11 | + |
| 12 | + return { |
| 13 | + endpoint: process.env.SYNC_SERVICE!, |
| 14 | + token: token |
| 15 | + }; |
| 16 | + } |
| 17 | + |
| 18 | + async uploadData(database: AbstractPowerSyncDatabase) { |
| 19 | + const batch = await database.getCrudBatch(); |
| 20 | + if (batch == null) { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + const entries: any[] = []; |
| 25 | + for (const op of batch.crud) { |
| 26 | + entries.push({ |
| 27 | + table: op.table, |
| 28 | + op: op.op, |
| 29 | + id: op.id, |
| 30 | + data: op.opData |
| 31 | + }); |
| 32 | + } |
| 33 | + |
| 34 | + const response = await fetch(`${process.env.BACKEND}/api/data/`, { |
| 35 | + method: 'POST', |
| 36 | + headers: {'Content-Type': 'application/json'}, |
| 37 | + body: JSON.stringify({batch: entries}), |
| 38 | + }); |
| 39 | + if (response.status !== 200) { |
| 40 | + throw new Error(`Server returned HTTP ${response.status}: ${await response.text()}`); |
| 41 | + } |
| 42 | + |
| 43 | + await batch?.complete(); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +export const LIST_TABLE = 'lists'; |
| 48 | +export const TODO_TABLE = 'todos'; |
| 49 | + |
| 50 | +const todos = new Table( |
| 51 | + { |
| 52 | + list_id: column.text, |
| 53 | + created_at: column.text, |
| 54 | + completed_at: column.text, |
| 55 | + description: column.text, |
| 56 | + created_by: column.text, |
| 57 | + completed_by: column.text, |
| 58 | + completed: column.integer, |
| 59 | + photo_id: column.text |
| 60 | + }, |
| 61 | + { indexes: { list: ['list_id'] } } |
| 62 | +); |
| 63 | + |
| 64 | +const lists = new Table({ |
| 65 | + created_at: column.text, |
| 66 | + name: column.text, |
| 67 | + owner_id: column.text |
| 68 | +}); |
| 69 | + |
| 70 | +export const AppSchema = new Schema({ |
| 71 | + lists, |
| 72 | + todos |
| 73 | +}); |
| 74 | + |
| 75 | +export type Database = (typeof AppSchema)['types']; |
| 76 | +export type TodoRecord = Database['todos']; |
| 77 | +export type ListRecord = Database['lists']; |
0 commit comments