Ebert
Ebert
TTCTheo's Typesafe Cult
Created by utdev on 1/22/2024 in #questions
Check for string to not be empty?
If you want to allow empty strings to pass on this verification you can use a logic like that:
if (
!gender && gender !== "" ||
!firstname && firstname !== ""||
!lastname && lastname !== ""
....
)
if (
!gender && gender !== "" ||
!firstname && firstname !== ""||
!lastname && lastname !== ""
....
)
7 replies
TTCTheo's Typesafe Cult
Created by utdev on 1/22/2024 in #questions
Check for string to not be empty?
Hello, one way to improve your code is check for falsy values using the ! operator For example, instead of checking if theses values are null or undefined like this:
if (
gender === undefined ||
gender === null ||
firstname === undefined ||
firstname === null ||
lastname === undefined ||
lastname === null ||
)
if (
gender === undefined ||
gender === null ||
firstname === undefined ||
firstname === null ||
lastname === undefined ||
lastname === null ||
)
You can check if the value is falsy with the ! operator:
if (
!gender ||
!firstname ||
!lastname
)
if (
!gender ||
!firstname ||
!lastname
)
Have a quick look about checking for falsy values in Javascript on this article: https://www.freecodecamp.org/news/falsy-values-in-javascript/
7 replies
TTCTheo's Typesafe Cult
Created by ForcedToCode on 1/20/2024 in #questions
Typescript ExpressJS middleware for jwt auth
There is another way to do this that is recommended by the express using the res.locals. Link to docs: https://expressjs.com/en/api.html#res.locals Basically, instead of using:
req.user = user
req.user = user
You, use:
res.locals.user = user
res.locals.user = user
The typescript will not complain because the res.locals are made to accept any content.
3 replies
TTCTheo's Typesafe Cult
Created by ForcedToCode on 1/20/2024 in #questions
Typescript ExpressJS middleware for jwt auth
Hello, you could create a type definition file to include the user property on the express Request. Example: Create an express.d.ts file in your project, this file could be located in a types folder or anywhere you want to inside src, with this content:
declare namespace Express {
export interface Request {
user: string | jwt.JwtPayload
}
}
declare namespace Express {
export interface Request {
user: string | jwt.JwtPayload
}
}
Doing this everywhere that you call the express request you will be able to use request.user. The bad side of this is if you try to access request.user in a route that does not have the verifyToken middleware you will get an runtime error, because the middleware is the one who saves the user value on the request.
3 replies