jeudi 7 novembre 2019

How to impliment a complex decision in javascript

Context:

We're writing logic for a signup component. If the user is not authenticated, the form should appear. If/when the user is authenticated it should redirect to one of several places. If there are unread messages, redirect to the first one. If there are no unread messages, redirect to the dashboard.

There is one more scenario we need to handle. When a new message arrives, a user can receive an email notification with a link to the signin form plus a query param with the ID of the specific message. Ex: /signin?new_message=42. In these situations, the signin form should appear if the user is not currently authenticated; if/when the user is authenticated, redirect to that specific message.

My Question:

How can we implement this in an elegant and extendible way?

I suspect that a state machine is the right tool for this job, but I am open to other approaches. I emphasized the word extendible because this is not code golf! I'm looking for a real-life solution that can scale gracefully to include additional business logic in the future.

NOTE: I don't actually care about javascript specifically, but StackOverflow best practices emphasize specificity and JS is the language I'm using. Therefore, an acceptible answer can use pseudo code as long it is conceptually compatible with javaScript. (Don't pseudo-code something that only works in Go)

Spoiler alert! Here's the WRONG answer:

if (authed && hasUnreadMessages) {
  redirect = `/messages/${fistUnreadMessageId}`;
}
if (authed && !hasUnreadMessages) {
  redirect = `/dashboard`
}
if (authed && clickFromEmail {
  redirect = `/messages/${messageIdFromQueryString}`
}
if (!authed) {
  redirect = null
}
...

^ A messy tangle of nested conditionals is the problem we're trying to solve.

NOT My Question

This is a real-life example, but the main goal of my question is to learn about implementing complex decision logic. So I am not interested in architectural solutions that avoid this logic entirely. Ex: "Create different forms/endoints to handle the different scenarios"

I'm also not interested in solutions that rely on a specific library. Ex: "You should just use ComplexSigninLibrary.js"

Product design or UX advice also misses the point of this question Ex: "It would be a better user experience to link directly from the email notifications to the new messages..."

Aucun commentaire:

Enregistrer un commentaire