Skip to content

Instantly share code, notes, and snippets.

@ddamko
Created May 5, 2021 22:43
Show Gist options
  • Save ddamko/59bbd52a62f90028db949691502ede35 to your computer and use it in GitHub Desktop.
Save ddamko/59bbd52a62f90028db949691502ede35 to your computer and use it in GitHub Desktop.
Creatiing a RxDb service class for use through out the application life cycle.
import { Injectable } from "@angular/core";
import { createRxDatabase, addRxPlugin, RxCollection, RxDatabase, RxJsonSchema } from "rxdb";
import * as pouchdbaAdapter from "pouchdb-adapter-idb";
import { BehaviorSubject } from "rxjs";
import { RxCollectionCreatorBase } from "rxdb/dist/types/types";
interface Collection {
name: string;
schema: RxJsonSchema;
}
@Injectable({ providedIn: "root" })
export class LocalDataService {
private _localDB: RxDatabase;
private _collections: { [name: string]: RxCollectionCreatorBase } = {};
public isReady = new BehaviorSubject<boolean>(false);
public collections: { [key: string]: RxCollection } = {};
constructor() {}
async CreateDB(name: string, type: string, collections: Collection[]) {
addRxPlugin(pouchdbaAdapter);
this._localDB = await createRxDatabase({
name: name,
adapter: type,
});
collections.forEach((collection) => {
this._collections[collection.name] = { schema: collection.schema };
});
this._localDB
.addCollections(this._collections)
.then((collections) => {
this.collections = collections;
})
.finally(() => this.isReady.next(true));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment