mirror of
https://github.com/renovatebot/renovate.git
synced 2025-01-13 07:26:26 +00:00
feat(result): Add unwrapOrNull
method (#24025)
This commit is contained in:
parent
b5e4b6c7ec
commit
ecbee400cb
2 changed files with 54 additions and 0 deletions
|
@ -159,6 +159,27 @@ describe('util/result', () => {
|
|||
const res = Result.err('oops');
|
||||
expect(() => res.unwrapOrThrow()).toThrow('oops');
|
||||
});
|
||||
|
||||
it('unwrapOrNull returns value for ok-result', () => {
|
||||
const res = Result.ok(42);
|
||||
expect(res.unwrapOrNull()).toBe(42);
|
||||
});
|
||||
|
||||
it('unwrapOrNull returns null for error result', () => {
|
||||
const res = Result.err('oops');
|
||||
expect(res.unwrapOrNull()).toBeNull();
|
||||
});
|
||||
|
||||
it('unwrapOrNull throws uncaught transform error', () => {
|
||||
const res = Result.ok(42);
|
||||
expect(() =>
|
||||
res
|
||||
.transform(() => {
|
||||
throw 'oops';
|
||||
})
|
||||
.unwrapOrNull()
|
||||
).toThrow('oops');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Transforming', () => {
|
||||
|
@ -373,6 +394,16 @@ describe('util/result', () => {
|
|||
const res = Result.wrap(Promise.reject('oops'));
|
||||
await expect(res.unwrapOrThrow()).rejects.toBe('oops');
|
||||
});
|
||||
|
||||
it('unwrapOrNull returns value for ok-result', async () => {
|
||||
const res = AsyncResult.ok(42);
|
||||
await expect(res.unwrapOrNull()).resolves.toBe(42);
|
||||
});
|
||||
|
||||
it('unwrapOrNull returns null for error result', async () => {
|
||||
const res = AsyncResult.err('oops');
|
||||
await expect(res.unwrapOrNull()).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Transforming', () => {
|
||||
|
|
|
@ -362,6 +362,22 @@ export class Result<T extends Val, E extends Val = Error> {
|
|||
throw this.res.err;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ok-value or `null`.
|
||||
* When error was uncaught during transformation, it's being re-thrown here.
|
||||
*/
|
||||
unwrapOrNull(): T | null {
|
||||
if (this.res.ok) {
|
||||
return this.res.val;
|
||||
}
|
||||
|
||||
if (this.res._uncaught) {
|
||||
throw this.res.err;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the ok-value, sync or async way.
|
||||
*
|
||||
|
@ -672,6 +688,13 @@ export class AsyncResult<T extends Val, E extends Val>
|
|||
return result.unwrapOrThrow();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ok-value or `null`.
|
||||
*/
|
||||
unwrapOrNull(): Promise<T | null> {
|
||||
return this.asyncResult.then<T | null>((res) => res.unwrapOrNull());
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the ok-value, sync or async way.
|
||||
*
|
||||
|
|
Loading…
Reference in a new issue