diff --git a/src/__tests__/remote-data.spec.ts b/src/__tests__/remote-data.spec.ts index 032eee7..fd74c31 100644 --- a/src/__tests__/remote-data.spec.ts +++ b/src/__tests__/remote-data.spec.ts @@ -719,5 +719,20 @@ describe('RemoteData', () => { expect(success(1).exists(p)).toBe(true); }); }); + describe('recover', () => { + const f = (error: string) => (error === 'foo' ? some(1) : none); + it('initial', () => { + expect(initialRD.recover(f)).toBe(initialRD); + }); + it('pending', () => { + expect(pendingRD.recover(f)).toBe(pendingRD); + }); + it('failure', () => { + expect(failure('foo').recover(f)).toEqual(success(1)); + }); + it('success', () => { + expect(successRD.recover(f)).toBe(successRD); + }); + }); }); }); diff --git a/src/remote-data.ts b/src/remote-data.ts index 0495518..d33f1dd 100644 --- a/src/remote-data.ts +++ b/src/remote-data.ts @@ -347,6 +347,13 @@ export class RemoteInitial { exists(p: Predicate): boolean { return false; } + + /** + * Processes failure error into new RemoteData if function f return some value + */ + recover(f: (error: L) => Option): RemoteData { + return this; + } } export class RemoteFailure { @@ -633,6 +640,13 @@ export class RemoteFailure { exists(p: Predicate): boolean { return false; } + + /** + * Processes failure error into new RemoteData if function f return some value + */ + recover(f: (error: L) => Option): RemoteData { + return f(this.error).fold>(this, success); + } } export class RemoteSuccess { @@ -919,6 +933,13 @@ export class RemoteSuccess { exists(p: Predicate): boolean { return p(this.value); } + + /** + * Processes failure error into new RemoteData if function f return some value + */ + recover(f: (error: L) => Option): RemoteData { + return this; + } } export class RemotePending { @@ -1210,6 +1231,13 @@ export class RemotePending { exists(p: Predicate): boolean { return false; } + + /** + * Processes failure error into new RemoteData if function f return some value + */ + recover(f: (error: L) => Option): RemoteData { + return this; + } } /**