Skip to content

Commit 953d550

Browse files
committed
fix: align extension storage 'set' and 'observeAll' with pouchdb storage behavior
deleting a wallet does: 1. delete it from repository 2. check remaining wallets, activate if some wallet exists there was a bug where step 2. would find the wallet that was just deleted and try to activate it, because extension storage 'observeAll' emits an slightly later
1 parent d590164 commit 953d550

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

apps/browser-extension-wallet/src/lib/scripts/background/storage/extension-document-store.ts

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* eslint-disable @typescript-eslint/ban-types */
22
import { storage as sdkStorage } from '@cardano-sdk/wallet';
3-
import { EMPTY, filter, from, map, mergeMap, Observable, of, share } from 'rxjs';
3+
import { EMPTY, filter, from, map, mergeMap, Observable, of, share, firstValueFrom } from 'rxjs';
44
import { Logger } from 'ts-log';
55
import { contextLogger, fromSerializableObject, toSerializableObject } from '@cardano-sdk/util';
66
import { ExtensionStore } from './extension-store';
@@ -10,8 +10,9 @@ export type DocumentChange<T> = {
1010
newValue?: T;
1111
};
1212

13-
const undefinedIfEmpty = <T>(value: T | undefined): T | undefined => {
14-
if (typeof value === 'object' && (value === null || Object.keys(value).length === 0)) return undefined;
13+
const undefinedIfEmptyObj = <T>(value: T | undefined): T | undefined => {
14+
if (typeof value === 'object' && !Array.isArray(value) && (value === null || Object.keys(value).length === 0))
15+
return undefined;
1516
// eslint-disable-next-line consistent-return
1617
return value;
1718
};
@@ -34,8 +35,8 @@ export class ExtensionDocumentStore<T extends {}> extends ExtensionStore impleme
3435
filter(({ key }) => key === docId),
3536
map(
3637
({ change }): DocumentChange<T> => ({
37-
oldValue: undefinedIfEmpty(change.oldValue),
38-
newValue: undefinedIfEmpty(change.newValue)
38+
oldValue: undefinedIfEmptyObj(change.oldValue),
39+
newValue: undefinedIfEmptyObj(change.newValue)
3940
})
4041
),
4142
share()
@@ -54,12 +55,18 @@ export class ExtensionDocumentStore<T extends {}> extends ExtensionStore impleme
5455

5556
set(doc: T): Observable<void> {
5657
this.logger.debug('set', doc);
58+
const storageChange = firstValueFrom(this.documentChange$);
5759
return from(
58-
(this.idle = this.idle.then(() =>
59-
this.storage.set({
60+
(this.idle = this.idle.then(async () => {
61+
await this.storage.set({
6062
[this.docId]: toSerializableObject(doc)
61-
})
62-
))
63+
});
64+
// do not emit until documentChange$ emits
65+
// in order to avoid race conditions:
66+
// users expect `observeAll` to emit new value when subscribing
67+
// to it immediatelly after `set` emits
68+
await storageChange;
69+
}))
6370
);
6471
}
6572

0 commit comments

Comments
 (0)