-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathindex.ts
150 lines (129 loc) · 4.22 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
import fs from 'node:fs';
import { Worker } from 'node:worker_threads';
import {
createBaseLogger,
createLogger,
LogLevel,
PowerSyncDatabase,
SyncStreamConnectionMethod
} from '@powersync/node';
import { app, BrowserWindow, ipcMain, MessagePortMain } from 'electron';
import { AppSchema, BackendConnector } from './powersync';
const baseLogger = createBaseLogger();
baseLogger.useDefaults({ defaultLevel: LogLevel.WARN });
const logger = createLogger('PowerSyncDemo');
// This allows TypeScript to pick up the magic constants that's auto-generated by Forge's Webpack
// plugin that tells the Electron app where to look for the Webpack-bundled app code (depending on
// whether you're running in development or production).
declare const MAIN_WINDOW_WEBPACK_ENTRY: string;
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: string;
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
app.quit();
}
const userDataDirectory = app.getPath('userData');
try {
if (!fs.existsSync(userDataDirectory)) {
fs.mkdirSync(userDataDirectory);
}
} catch (e) {
console.error('Could not create database directory', e);
}
console.log('Storing data in ', userDataDirectory);
const database = new PowerSyncDatabase({
schema: AppSchema,
database: {
dbFilename: 'test.db',
dbLocation: userDataDirectory,
openWorker(_, options) {
return new Worker(new URL('./worker.ts', import.meta.url), options);
}
},
logger
});
const createWindow = (): void => {
// Create the browser window.
const mainWindow = new BrowserWindow({
height: 600,
width: 800,
webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY
}
});
// and load the index.html of the app.
mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
database.connect(new BackendConnector(), { connectionMethod: SyncStreamConnectionMethod.HTTP });
const forwardSyncStatus = (port: MessagePortMain) => {
port.postMessage(database.currentStatus.toJSON());
const unregister = database.registerListener({
statusChanged(status) {
port.postMessage(status.toJSON());
}
});
port.once('close', unregister);
};
const forwardWatchResults = (sql: string, args: any[], port: MessagePortMain) => {
const abort = new AbortController();
port.once('close', () => abort.abort());
database.watchWithCallback(
sql,
args,
{
onResult(results) {
port.postMessage(results.rows._array);
},
onError(error) {
console.error(`Watch ${sql} with ${args} failed`, error);
}
},
{ signal: abort.signal }
);
};
ipcMain.on('port', (portEvent) => {
const [port] = portEvent.ports;
port.start();
port.on('message', (event) => {
const { method, payload } = event.data;
switch (method) {
case 'syncStatus':
forwardSyncStatus(port);
break;
case 'watch':
const { sql, args } = payload;
forwardWatchResults(sql, args, port);
break;
}
});
});
ipcMain.handle('get', async (_, sql: string, args: any[]) => {
return await database.get(sql, args);
});
ipcMain.handle('getAll', async (_, sql: string, args: any[]) => {
return await database.getAll(sql, args);
});
createWindow();
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.