Skip to content

Commit f26c779

Browse files
feat: add resultToPromise transformer (#170)
1 parent 6fa65c3 commit f26c779

File tree

4 files changed

+33
-1
lines changed

4 files changed

+33
-1
lines changed

src/result/pubcli_api.spec.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
import { Result, fail, ok, result } from './public_api'
1+
import { Result, fail, ok, result, resultToPromise } from './public_api'
22

33
describe('result api', () => {
44
it('should export', () => {
55
expect(fail(Error('Test'))).toBeInstanceOf(Result)
66
expect(ok(1)).toBeInstanceOf(Result)
77
expect(result(() => true, 1, Error('Test'))).toBeInstanceOf(Result)
8+
expect(typeof resultToPromise).toEqual('function')
89
})
910
})

src/result/public_api.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * from './result'
22
export * from './result.factory'
33
export * from './result.interface'
4+
export * from './transformers/result-to-promise'
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { fail, ok } from '../result.factory'
2+
import { IResult } from '../result.interface'
3+
import { resultToPromise } from './result-to-promise'
4+
5+
describe('resultToPromise', () => {
6+
it('should map', () => {
7+
const sut = new Promise<IResult<string, Error>>(resolve => resolve(ok('test')))
8+
9+
return sut
10+
.then(resultToPromise)
11+
.then(result => expect(result).toEqual('test'))
12+
.catch(() => expect(false).toBe(true))
13+
})
14+
15+
it('should catch w/ fail result', () => {
16+
const sut = new Promise<IResult<string, Error>>(resolve => resolve(fail(new Error('test error'))))
17+
18+
return sut
19+
.then(resultToPromise)
20+
.then(() => expect(false).toBe(true))
21+
.catch(error => expect(error).toEqual(new Error('test error')))
22+
})
23+
24+
})
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { IResult } from '../result.interface'
2+
3+
export const resultToPromise =
4+
<TOk, TFail>(result: IResult<TOk, TFail>): Promise<TOk> => result.isOk()
5+
? Promise.resolve(result.unwrap() as TOk)
6+
: Promise.reject(result.unwrapFail() as TFail)

0 commit comments

Comments
 (0)