1.0.11 ā€¢ Published 6 months ago

@sefr/result v1.0.11

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

@sefr/result āœØ

What does it do ? šŸ’”

Provide a simple implementation of the Operation Result Pattern for TypeScript to avoid boilerplate code.

Compatibility šŸ”§

TypeScriptEcmaScript
>= 2.8.0>= ES2015

Dependencies šŸŽ±

This package is dependencies-free.

Installation šŸ’¾

Nothing more than :

npm i -S @sefr/result

How to use šŸ“š

āœ… Returning a success without content :

import { Result } from "@sefr/result";

function doSomething(...args: Array<unknown>): Result<Error> {
    return Result.ok();
}

const toto: Result<Error> = doSomething();

if (toto.isFailure) {
	// do something...
}

āœ… Returning a success with a string content :

import { Result } from "@sefr/result";

function doSomething(...args: Array<unknown>): Result<string | Error> {
	return Result.ok("Operation successful !");
}

const toto: Result<string | Error> = doSomething();

if (toto.isFailure) {
	// do something...
} else {
	const titi = toto.value; // "Operation successful"
}

āœ… Returning a failure with some custom error :

import { Result } from "@sefr/result";

class SomeCustomError extends Error {
	constructor(public readonly someMoreInformation: Record<string, string>, message: string) {
		super(message);
	}
}

function doSomething(...args: Array<unknown>): Result<string | SomeCustomError> {
	return Result.failure(new SomeCustomError(
		{ id: "5", someMoreInfo: "stuff & co..." },
        "Oops! Something went wrong !"
    ));
}

const toto: Result<string | SomeCustomError> = doSomething();

if (toto.isFailure) {
	const titi = toto.value; // SomeCustomError
	// do something...
}

Incorrect usages āŒ

āŒ Returning an error as successful operation is not allowed, TypeScript will not allow it :

import { Result } from "@sefr/result";

function doSomething(...args: Array<unknown>): Result<string | Error> {
	return Result.ok(new Error("Operation successfull !"));
}

āŒ Returning a failure without any reason (understand Error), TypeScript will also fail on build :

import { Result } from "@sefr/result";

function doSomething(...args: Array<unknown>): Result<string | Error> {
	return Result.failure();
}

Credits šŸ“Ž

License šŸ“œ

This software is available under the MIT License. See the LICENSE file for more informations.

ā¬†ļø Go back to top

1.0.9

8 months ago

1.0.8

9 months ago

1.0.7

10 months ago

1.0.6

10 months ago

1.0.11

6 months ago

1.0.10

7 months ago

1.0.5

11 months ago

1.0.4

11 months ago

1.0.3

12 months ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago