Created
February 23, 2022 12:18
-
-
Save shivam-tripathi/40b230bb73b2bbc1926a53bb85279be8 to your computer and use it in GitHub Desktop.
Result passing in Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Context } from '@src/helpers/context'; | |
import QError from '@src/helpers/error'; | |
import is from 'is_js'; | |
/** | |
* Contains result which can be error or ok | |
*/ | |
export default class Result<T> { | |
private readonly value?: T; | |
private readonly error?: Error; | |
private readonly context?: Context; | |
constructor({ err: error, ok: value, ctx }: { err?: string, ok?: T, ctx?: Context }) { | |
if ((is.existy(error) && is.existy(value)) || (is.not.existy(error) && is.not.existy(value))) { | |
throw new QError('Incorrect Result initialization', 'result.INITIALIZE', { | |
error, | |
value, | |
}); | |
} | |
this.error = new Error(error); | |
this.value = value; | |
this.context = ctx; | |
} | |
isErr(): boolean { | |
return is.existy(this.error); | |
} | |
isOk(): boolean { | |
return is.existy(this.value); | |
} | |
err(): Error { | |
if (is.not.existy(this.error)) { | |
throw new QError('Cannot extract error when it is not present', 'result.ERROR', { | |
error: this.error, | |
value: this.value, | |
}); | |
} | |
return this.error; | |
} | |
ok(): T { | |
if (is.not.existy(this.value)) { | |
throw new QError('Cannot extract ok when it is not present', 'result.OK', { | |
error: this.error, | |
value: this.value, | |
}); | |
} | |
return this.value; | |
} | |
ctx(): Context | undefined { | |
return this.context; | |
} | |
static ok<T>(val: T, ctx?: Context): Result<T> { | |
return new Result<T>({ ok: val, ctx }); | |
} | |
static err<T>(msg: string, ctx?: Context): Result<T> { | |
return new Result<T>({ err: msg, ctx }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example