Skip to content

Instantly share code, notes, and snippets.

@CallumVass
Created September 17, 2020 14:22
Show Gist options
  • Save CallumVass/175baf84382b3efd876c5c4c0b649477 to your computer and use it in GitHub Desktop.
Save CallumVass/175baf84382b3efd876c5c4c0b649477 to your computer and use it in GitHub Desktop.
TS/F#
export interface ErrorValue {
ErrorValue: string;
}
export interface ResultValue<T> {
ResultValue: T;
}
export interface ErrorResult {
Case: "Error";
Fields: ErrorValue;
}
export interface OkResult<T> {
Case: "Ok";
Fields: ResultValue<T>;
}
export type Result<T> = OkResult<T> | ErrorResult;
export const handleResultType = <T>(
data: Result<T>,
okCallBack: (_: T) => void,
errorCallBack: (_: string) => void
) => {
switch (data.Case) {
case "Ok":
return okCallBack(data.Fields.ResultValue);
case "Error":
return errorCallBack(data.Fields.ErrorValue);
}
};
//usage
login()
.then((response) => response.json() as Promise<Result<Token>>)
.then((data) => {
handleResultType(
data,
(okValue: Token) => {
console.log("OK", okValue);
},
(error) => {
console.log("ERROR", error);
}
);
});
type CreateUserRequest =
{ Email: string
Password: string
PasswordConfirmation: string }
type CreateUserRequest = {
Email: string;
Password: string;
PasswordConfirmation: string;
};
@AngelMunoz
Copy link

if you want to go the full promise way I'd suggest something like this in the handleResultType

export const handleResultType = <T>(data: Result<T>) => {
  switch (data.Case) {
    case "Ok":
      return Promise.resolve(data.Fields.ResultValue);
    case "Error":
      return Promise.reject(data.Fields.ErrorValue);
  }
};

it should work somewhat like this (just wrote it from memory didn't test it)

login()
  .then((response) => response.json() as Promise<Result<Token>>)
  .then(handleResultType)
  .then((okValue: Token) => {
    console.log("OK", okValue);
  })
  .catch((error) => {
    console.log("ERROR", error);
  });

and it also should save you from nesting callbacks

@CallumVass
Copy link
Author

Thanks, that looks a lot cleaner 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment