Skip to content

Commit

Permalink
collect opend database and close inside decorator in parallel
Browse files Browse the repository at this point in the history
  • Loading branch information
JonataB committed Dec 3, 2024
1 parent 7b54be2 commit d0df0cc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
10 changes: 6 additions & 4 deletions projects/ngx-indexed-db/src/lib/decorators.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { closeDatabase } from './ngx-indexed-db';
import { closeDatabase, openedDatabases } from './ngx-indexed-db';

export function CloseDbConnection(): MethodDecorator {
return function (_target: any, _propertyKey: string, descriptor: PropertyDescriptor): PropertyDescriptor {
Expand All @@ -11,10 +11,12 @@ export function CloseDbConnection(): MethodDecorator {
if (result instanceof Observable) {
return result.pipe(
finalize(async () => {
const db: IDBDatabase | null = this.getDatabaseInstance();
if (db) {
const promises = openedDatabases.map(async (db: IDBDatabase) => {
await closeDatabase(db);
}
console.log('Database connection closed: ', db.name);
});
await Promise.all(promises);
openedDatabases.length = 0;
})
);
}
Expand Down
3 changes: 3 additions & 0 deletions projects/ngx-indexed-db/src/lib/ngx-indexed-db.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { ObjectStoreMeta } from './ngx-indexed-db.meta';
import { Observable, Subscriber } from 'rxjs';

export const openedDatabases: IDBDatabase[] = [];

export function openDatabase(
indexedDB: IDBFactory,
dbName: string,
Expand All @@ -15,6 +17,7 @@ export function openDatabase(
let db: IDBDatabase;
request.onsuccess = (event: Event) => {
db = request.result;
openedDatabases.push(db);
resolve(db);
};
request.onerror = (event: Event) => {
Expand Down

0 comments on commit d0df0cc

Please sign in to comment.