Skip to content

Commit

Permalink
fix: align extension storage 'set' and 'observeAll' with pouchdb stor…
Browse files Browse the repository at this point in the history
…age 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
  • Loading branch information
mkazlauskas committed Dec 16, 2024
1 parent d590164 commit 953d550
Showing 1 changed file with 16 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/ban-types */
import { storage as sdkStorage } from '@cardano-sdk/wallet';
import { EMPTY, filter, from, map, mergeMap, Observable, of, share } from 'rxjs';
import { EMPTY, filter, from, map, mergeMap, Observable, of, share, firstValueFrom } from 'rxjs';
import { Logger } from 'ts-log';
import { contextLogger, fromSerializableObject, toSerializableObject } from '@cardano-sdk/util';
import { ExtensionStore } from './extension-store';
Expand All @@ -10,8 +10,9 @@ export type DocumentChange<T> = {
newValue?: T;
};

const undefinedIfEmpty = <T>(value: T | undefined): T | undefined => {
if (typeof value === 'object' && (value === null || Object.keys(value).length === 0)) return undefined;
const undefinedIfEmptyObj = <T>(value: T | undefined): T | undefined => {
if (typeof value === 'object' && !Array.isArray(value) && (value === null || Object.keys(value).length === 0))
return undefined;
// eslint-disable-next-line consistent-return
return value;
};
Expand All @@ -34,8 +35,8 @@ export class ExtensionDocumentStore<T extends {}> extends ExtensionStore impleme
filter(({ key }) => key === docId),
map(
({ change }): DocumentChange<T> => ({
oldValue: undefinedIfEmpty(change.oldValue),
newValue: undefinedIfEmpty(change.newValue)
oldValue: undefinedIfEmptyObj(change.oldValue),
newValue: undefinedIfEmptyObj(change.newValue)
})
),
share()
Expand All @@ -54,12 +55,18 @@ export class ExtensionDocumentStore<T extends {}> extends ExtensionStore impleme

set(doc: T): Observable<void> {
this.logger.debug('set', doc);
const storageChange = firstValueFrom(this.documentChange$);
return from(
(this.idle = this.idle.then(() =>
this.storage.set({
(this.idle = this.idle.then(async () => {
await this.storage.set({
[this.docId]: toSerializableObject(doc)
})
))
});
// do not emit until documentChange$ emits
// in order to avoid race conditions:
// users expect `observeAll` to emit new value when subscribing
// to it immediatelly after `set` emits
await storageChange;
}))
);
}

Expand Down

0 comments on commit 953d550

Please sign in to comment.