Skip to content

Commit

Permalink
feat: introduce resultToObservable (#195)
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickmichalina authored Dec 22, 2022
1 parent 744a69c commit bd78b80
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/result/pubcli_api.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Result, fail, ok, result, resultToPromise } from './public_api'
import { Result, fail, ok, result, resultToPromise, resultToObservable } from './public_api'

describe('result api', () => {
it('should export', () => {
expect(fail(Error('Test'))).toBeInstanceOf(Result)
expect(ok(1)).toBeInstanceOf(Result)
expect(result(() => true, 1, Error('Test'))).toBeInstanceOf(Result)
expect(typeof resultToPromise).toEqual('function')
expect(typeof resultToObservable).toEqual('function')
})
})
1 change: 1 addition & 0 deletions src/result/public_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export * from './result.interface'
export * from './transformers/result-to-promise'
export * from './transformers/try-catch-to-result'
export * from './transformers/unwrap-result'
export * from './transformers/result-to-observable'
32 changes: 32 additions & 0 deletions src/result/transformers/result-to-observable.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { fail, ok } from '../result.factory'
import { resultToObservable } from './result-to-observable'

describe(resultToObservable.name, () => {
it('should be ok', done => {
const result = ok<string, Error>('hello')
const sut = resultToObservable(result)

sut
.subscribe({
next: v => {
expect(v).toEqual('hello')
done()
},
error: done
})
})

it('should be ok', done => {
const result = fail<string, Error>(new Error('I failed, sorry.'))
const sut = resultToObservable(result)

sut
.subscribe({
error: (v: Error) => {
expect(v.message).toEqual('I failed, sorry.')
done()
},
next: done
})
})
})
10 changes: 10 additions & 0 deletions src/result/transformers/result-to-observable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Observable, of, throwError } from 'rxjs'
import { IResult } from '../result.interface'

export function resultToObservable<TOk, TFail>(result: IResult<TOk, TFail>): Observable<TOk> {
if (result.isOk()) {
return of(result.unwrap())
} else {
return throwError(() => result.unwrapFail())
}
}

0 comments on commit bd78b80

Please sign in to comment.