samedi 20 mars 2021

typescript return null found pattern question

If i have an interface User like so:

export interface User {
  username: string;
  hash: string;
}

and i have a method signature that looks like this that returns a User typically from a database

function getUser(username: string): Promise<User>

Then in a calling program, I'd want to do something like this:

  const user: User = await getUser(username);
  if (user && (await passMatch(password, user.hash))) {
    return genToken();
  }

What are some popular patterns of return types and validation combos on user not found?

In java (right or wrong) i'd return null and do a null check.

Is a throw not found error and catch it, a good pattern? I can't reconcile not finding one is not an error.

Aucun commentaire:

Enregistrer un commentaire