You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This package is created to handle returns and errors in a better way, using functional concept Either.
it facilitates the manner that you handle the api responses
Usage:
import{left,right}from'@andrejunqueira/either_js';asyncfunctiongetUser(){//You can return left or right to be hanledtry{constresponse=awaitaxios.get('https://apiurl.com')//Your request validations...if(response.status==='400'){returnleft("Something went wrong");}//Everithing is ok...returnright(response.data);}catch(error){//Something went wrong...returnleft(error);}}
fold
/// USAGEconstmyUser=awaitgetUser();functionwhenLeft(data){//Do something when go wrong}functionwhenRight(data){// Do somethisn when go right !}myUser.fold(whenLeft,whenRight);//ORmyUser.fold((error)=>console.log(error),(success)=>console.log(success));// You can do checks if neededif(myUser.isLeft()){//Do something}if(myUser.isRight()){//Do something}
constmyUser=awaitgetUser();constsuccessValue=myUser.getOrNull();console.log(successValue)//if something go wrong the successValue will be null
getOrDefault
constmyUser=awaitgetUser();constsuccessValue=myUser.getOrDefault('Default data !');console.log(successValue)//if something go wrong the successValue will be ["Default data !]"
map
classUser{name;constructor(name){this.name=name;}printName(){console.log(this.name);}}constmyUser=awaitgetUser();//the success value will be mapped to anything you return from itconstvalue=myUser.map((value)=>newUser(value));//after to be mapped you can use any other methods like fold for examplevalue.fold((error)=>console.log(),(user)=>user.printName(),);
mapError
constmyUser=awaitgetUser();//the same as map, but the error value will be mappedconstvalue=myUser.mapError((value)=>newError(value));//after to be mapped you can use any other methods like fold for examplevalue.fold((error)=>console.log(error.message),(success)=>console.log(success),);
Thats it !!
About
This package is created to handle returns and errors in a better way, using functional concept Either.