Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix middleware types #198

Open
sivertschou opened this issue Oct 30, 2022 · 2 comments
Open

Fix middleware types #198

sivertschou opened this issue Oct 30, 2022 · 2 comments
Labels
code-enhancement Improvements to the codebase help wanted Extra attention is needed

Comments

@sivertschou
Copy link
Owner

As per now we have the type AuthenticatedRequest<T> being used for our endpoints requiring a user's token. I have not yet found a way to correctly use the types that model the scenarios that we actually want.

What we want:
We'll use post("/me/workout") as our example endpoint. We only wish to accept requests with a token. If a token is provided, we will call the fictional function addWorkout, if not, we will send a response rejecting the request.

To ensure that the request contains a token, we use the middleware function authenticateToken, who's job is to validate the token and make the token's data easily available for the addWorkout function. In Express, we usually append the data we want in the authenticated function to the request parameter, but this leads to some issues with our types.

Intuitively, authenticateToken's request parameter should be Request<T>, and addWorkout's request parameter should be something like AuthenticatedRequest<T>, which should be an extension of Request<T>, where a username: string field is added.
We want the

As per now out AuthenticatedRequest<T> has an optional field to make the types compile, username?: string. We obviously want it to be required, but i can't find a way to get the types and the Express middleware workflow to work 🥲

@sivertschou sivertschou added help wanted Extra attention is needed code-enhancement Improvements to the codebase labels Oct 30, 2022
@sivertschou
Copy link
Owner Author

The best i've come up with is adding the middleware function as a type guard at the beginning of every function that should be authorized. I'm not too satisfied with it, but i think it is an improvement.

@sivertschou
Copy link
Owner Author

Being partly solved in #193

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
code-enhancement Improvements to the codebase help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant