Open sivertschou opened 2 years ago
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.
Being partly solved in #193
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 functionaddWorkout
, 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 theaddWorkout
function. In Express, we usually append the data we want in the authenticated function to therequest
parameter, but this leads to some issues with our types.Intuitively,
authenticateToken
's request parameter should beRequest<T>
, andaddWorkout
's request parameter should be something likeAuthenticatedRequest<T>
, which should be an extension ofRequest<T>
, where ausername: string
field is added. We want theAs 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 🥲