OPFS RxStorage (beta)
The OPFS RxStorage for RxDB is built on top of the File System Access API which is available in all modern browsers. It provides an API to access a sandboxed private file system to persistently store and retrieve data. Compared to other persistend storage options in the browser (like IndexedDB), the OPFS API has a way better performance.
The OPFS API can only be accessed in a WebWorker. It cannot be accessed in the main JavaScript process, an iFrame or even a SharedWorker.
Pros
- It is really fast, about 3-4 times faster than IndexedDB
- It has a small build size.
- It allows to use boolean values as index.
Cons
- It is part of the RxDB Premium plugin that must be purchased.
- It must be used in a WebWorker which complicates the setup a bit.
- It is in beta mode at the moment which means it can include breaking changes without a RxDB major version increment.
Usage
The OPFS storage itself must run inside a WebWorker. Therefore we use the Worker RxStorage and let it point to the prebuild opfs.worker.js
file that comes shipped with RxDB Premium.
import {
createRxDatabase
} from 'rxdb';
import { getRxStorageWorker } from 'rxdb-premium/plugins/storage-worker';
import { RxStorageOPFSStatics } from 'rxdb-premium/plugins/storage-opfs';
const database = await createRxDatabase({
name: 'mydatabase',
storage: getRxStorageWorker(
{
statics: RxStorageOPFSStatics,
/**
* This file must be statically served from a webserver.
* You might want to first copy it somewhere outside of
* your node_modules folder.
*/
workerInput: 'node_modules/rxdb-premium/dist/workers/opfs.worker.js'
}
)
});
Building a custom worker
When you want to run additional plugins like storage wrappers or replication inside of the worker, you have to build your own worker.js
file. You can do that similar to other workers by calling exposeWorkerRxStorage
like described in the worker storage plugin
// inside of worker.js
import { getRxStorageOPFS } from 'rxdb-premium/plugins/storage-opfs';
import { exposeWorkerRxStorage } from 'rxdb-premium/plugins/storage-worker';
const storage = getRxStorageOPFS();
exposeWorkerRxStorage({
storage
});