src/app/core/database/pouchdb/memory-pouch-database.ts

Description

An alternative implementation of PouchDatabase that uses the in-memory adapter not persisting any data after the page is closed.

Extends

PouchDatabase

Relationships

Used by

No results matching.

Depends on

Index

Properties
Methods

Constructor

constructor(dbName: string, globalSyncState: SyncStateSubject, ngZone?: NgZone)
Parameters :
Name Type Optional
dbName string No
globalSyncState SyncStateSubject No
ngZone NgZone Yes

Properties

adapter
Type : string
Default value : "indexeddb"
Inherited from PouchDatabase

The PouchDB adapter to use for local storage. Set by the factory/resolver before calling init(). Default: "indexeddb" (the newer adapter). Use "idb" for the legacy adapter.

Protected changesFeed
Type : Subject<any>
Inherited from PouchDatabase

An observable that emits a value whenever the PouchDB receives a new change. This change can come from the current user or remotely from the (live) synchronization

Protected databaseInitialized
Type : unknown
Default value : new Subject<void>()
Inherited from PouchDatabase
Protected Readonly destroy$
Type : unknown
Default value : new Subject<void>()
Inherited from PouchDatabase

trigger to unsubscribe any internal subscriptions

Protected indexPromises
Type : Promise<any>[]
Default value : []
Inherited from PouchDatabase

A list of promises that resolve once all the (until now saved) indexes are created

Protected pouchDB
Type : PouchDB.Database
Inherited from PouchDatabase

The reference to the PouchDB instance

Methods

init
init(dbName?: string)
Inherited from Database
Parameters :
Name Type Optional Description
dbName string Yes

the name for the database

Returns : void
Async allDocs
allDocs(options?: GetAllOptions)
Inherited from Database

Load all documents (matching the given PouchDB options) from the database. (see Database)

Normally you should rather use "getAll()" or another well typed method of this class instead of passing PouchDB specific options here because that will make your code tightly coupled with PouchDB rather than any other database provider.

Parameters :
Name Type Optional Description
options GetAllOptions Yes

PouchDB options object as in the normal PouchDB library

Returns : unknown
changes
changes()
Inherited from Database

Listen to changes to documents in the database. Use rxjs operators to filter for specific prefixes etc. if needed.

Returns : Observable<any>

observable which emits the filtered changes

Async destroy
destroy()
Inherited from Database

Destroy the database and all saved data

Returns : Promise<any>
Async get
get(id: string, options: GetOptions, returnUndefined?: boolean)
Inherited from Database

Load a single document by id from the database. (see Database)

Parameters :
Name Type Optional Default value Description
id string No

The primary key of the document to be loaded

options GetOptions No {}

Optional PouchDB options for the request

returnUndefined boolean Yes

(Optional) return undefined instead of throwing error if doc is not found in database

Returns : Promise<any>
getPouchDB
getPouchDB()
Inherited from PouchDatabase

Get the actual instance of the PouchDB

Returns : PouchDB.Database
Async getPouchDBOnceReady
getPouchDBOnceReady()
Inherited from PouchDatabase
isEmpty
isEmpty()
Inherited from Database

Check if a database is new/empty. Returns true if there are no documents in the database

Returns : Promise<boolean>
isInitialized
isInitialized()
Inherited from Database
Returns : boolean
Protected isNotificationsDatabase
isNotificationsDatabase()
Inherited from PouchDatabase

Check if this is a notifications database based on the database name. (may be used for special handling of notification DBs)

Returns : boolean
Async purge
purge(id: string)
Inherited from Database

Permanently purge a document and all its revisions from the local database.

Unlike remove, which creates a deletion tombstone that is synced, purge completely removes local data without affecting the remote database. This also emits a synthetic deletion event via the changes feed so that in-memory caches (entity stores) drop the purged entity.

Adapter limitation: The underlying PouchDB purge() API is only available on the indexeddb adapter (PouchDB 8+). On unsupported adapters PouchDB will throw its own error, which callers should handle (e.g. via try/catch + logging).

Example :
     false if the document did not exist locally (benign — desired state already achieved)
Parameters :
Name Type Optional Description
id string No

The document ID to purge

Returns : Promise<boolean>

true if the document was purged, false if the document did not exist locally (benign — desired state already achieved)

Async put
put(object: any, forceOverwrite: unknown)
Inherited from Database

Save a document to the database. (see Database)

Parameters :
Name Type Optional Default value Description
object any No

The document to be saved

forceOverwrite unknown No false

(Optional) Whether conflicts should be ignored and an existing conflicting document forcefully overwritten.

Returns : Promise<any>
Async putAll
putAll(objects: any[], forceOverwrite: unknown)
Inherited from Database

Save an array of documents to the database The save can partially fail and return a mix of success and error states in the array (e.g. [{ ok: true, ... }, { error: true, ... }])

Parameters :
Name Type Optional Default value Description
objects any[] No

the documents to be saved

forceOverwrite unknown No false

whether conflicting versions should be overwritten

Returns : Promise<any>

array with the result for each object to be saved, if any item fails to be saved, this returns a rejected Promise. The save can partially fail and return a mix of success and error states in the array (e.g. [{ ok: true, ... }, { error: true, ... }])

query
query(fun: string | unknown, options: QueryOptions)
Inherited from Database

Query data from the database based on a more complex, indexed request. (see Database)

This is directly calling the PouchDB implementation of this function. Also see the documentation there: https://pouchdb.com/api.html#query_database

Parameters :
Name Type Optional Description
fun string | unknown No

The name of a previously saved database index

options QueryOptions No

Additional options for the query, like a key. See the PouchDB docs for details.

Returns : Promise<any>
remove
remove(object: any)
Inherited from Database

Delete a document from the database (see Database)

Parameters :
Name Type Optional Description
object any No

The document to be deleted (usually this object must at least contain the _id and _rev)

Returns : any
Async reset
reset()
Inherited from Database

Reset the database state so a new one can be opened.

Returns : any
saveDatabaseIndex
saveDatabaseIndex(designDoc: any)
Inherited from Database

Create a database index to query() certain data more efficiently in the future. (see Database)

Also see the PouchDB documentation regarding indices and queries: https://pouchdb.com/api.html#query_database

Parameters :
Name Type Optional Description
designDoc any No

The PouchDB style design document for the map/reduce query

Returns : Promise<void>
Protected shouldSkipIndexUpdate
shouldSkipIndexUpdate(_existingDesignDoc: any)
Inherited from PouchDatabase

Whether to skip updating a design doc that differs from the local version. Overridden in RemotePouchDatabase to prevent older clients from overwriting indexes created by a newer app version on a shared server.

Parameters :
Name Type Optional
_existingDesignDoc any No
Returns : boolean
Protected Async subscribeChanges
subscribeChanges()
Inherited from PouchDatabase
Returns : any
Protected Async withReadRetry
withReadRetry<T>(operation: () => void)
Inherited from PouchDatabase
Type parameters :
  • T

Hook wrapping an idempotent read (get/allDocs/query) so subclasses can transparently retry transient failures.

The base implementation runs the operation exactly once (no retry). RemotePouchDatabase overrides this to re-issue reads that fail with a transient network abort/timeout, which recovers e.g. a connection gone stale after the tab was suspended. Only reads use this hook — writes must run exactly once and are never routed through it.

Parameters :
Name Type Optional
operation function No
Returns : Promise<T>
getAll
getAll(prefix: string)
Inherited from Database

Load all documents (with the given prefix) from the database.

Parameters :
Name Type Optional Default value Description
prefix string No ""

The string prefix of document ids that should be retrieved

Returns : Promise<Array<any>>
import { PouchDatabase } from "./pouch-database";
import PouchDB from "pouchdb-browser";
import memory from "pouchdb-adapter-memory";
import { SyncStateSubject } from "app/core/session/session-type";
import { SyncState } from "app/core/session/session-states/sync-state.enum";
import { NgZone } from "@angular/core";

/**
 * An alternative implementation of PouchDatabase that uses the in-memory adapter
 * not persisting any data after the page is closed.
 */
export class MemoryPouchDatabase extends PouchDatabase {
  constructor(
    dbName: string = "in-memory-db",
    globalSyncState: SyncStateSubject,
    ngZone?: NgZone,
  ) {
    super(dbName, globalSyncState, ngZone);
  }

  /**
   * Initialize the PouchDB with the in-memory adapter.
   * See {@link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules/pouchdb-adapter-memory}
   * @param dbName the name for the database
   */
  override init(dbName?: string) {
    PouchDB.plugin(memory);
    this.pouchDB = new PouchDB(dbName ?? this.dbName, { adapter: "memory" });
    this.databaseInitialized.complete();
    this.globalSyncState.next(SyncState.COMPLETED);
  }
}

results matching ""

    No results matching ""