driftWorkerMain function
A suitable entrypoint for a web worker aiming to make a drift database available to other browsing contexts.
This function will detect whether it is running in a shared or in a
dedicated worker. In either case, the openConnection
callback is invoked
to start a DriftServer that will serve drift database requests to clients.
When running in a shared worker, this function listens to
SharedWorkerGlobalScope.onConnect events and establishes message channels
with connecting clients to share a database.
In a dedicated worker, a DedicatedWorkerGlobalScope.postMessage
-construction
is used to establish a communication channel with clients.
To connect to this worker, the connectToDriftWorker function can be used.
As an example, a worker file could live in web/database_worker.dart
and
have the following content:
import 'dart:html';
import 'package:drift/drift.dart';
import 'package:drift/web.dart';
import 'package:drift/web/worker.dart';
void main() {
// Load sql.js library in the worker
WorkerGlobalScope.instance.importScripts('sql-wasm.js');
driftWorkerMain(() {
return WebDatabase.withStorage(DriftWebStorage.indexedDb('worker',
migrateFromLocalStorage: false, inWebWorker: true));
});
}
Depending on the build system you use, you can then compile this Dart web
worker with dart compile js
, build_web_compilers
or other tools.
The connectToDriftWorker method can be used in the main portion of your app to connect to a worker using driftWorkerMain.
The documentation contains additional information and an example on how to use workers with Dart and Drift.
Implementation
void driftWorkerMain(QueryExecutor Function() openConnection) {
final self = globalContext;
_RunningDriftWorker worker;
if (self is SharedWorkerGlobalScope) {
worker = _RunningDriftWorker(true, openConnection);
} else if (self is DedicatedWorkerGlobalScope) {
worker = _RunningDriftWorker(false, openConnection);
} else {
throw StateError('This worker is neither a shared nor a dedicated worker');
}
worker.start();
}