#Logger in functional component
21 messages · Page 1 of 1 (latest)
seems to me that you need a dependecy there and if so a functional middleware is not what you need here
i think you can achieve that with a class based middleware
Yes, I can achieve the Logger using Class based middleware, but that that class based middleware can't be used in main.ts with app.use() for Global Middleware
so why you need a logger there?
what exactly are you trying to log?
instead of console.log I am using logger
ok and what are you trying to log?
throw new BadRequestException(Missing query params for ${req.path}: ${missingParams.join(", ")});
this I want to log as well
i think that should be at the controller isnt?
if i were you i would do it at the controller so i do the validation at the controller in the specific route i need it for
Yup, but I don't want to repeat the Code, I am trying DRY, so doing this way, that's why I am checking for Logger in Functional Middleware, as I've achieved the Logger properly in class based middleware...
can you show me the code of how you are doing it
for Class based??
You can do manual dependency injection with function based middleware - instead of just the middleware, create a function that takes logger as an argumen, and returns the middleware function as a closure with the logger.
Then, in main, retrieve the logger from DI and pass it like so
app.use(getMiddleware(logger))
But, if you use Nest's logger abstraction, you don't need to use DI, you can just call new Logger(name) and use that. The loogger is gobal and proxies call to any custom logger configured with app.useLogger
Sorry but I didn't get you here
function getMiddleware(logger: Logger) {
return (req, res, next) => {
// do stuff
logger.log(stuff)
return next()
}
}
so you would have to instantiate the logger at the app file and then send the instance of this logger on the middleware correct?
if so maybe this would be more clear for him