Open yaldram opened 1 year ago
Hi, happy that the book was useful!
Let me answer your questions!
Why was this approach chosen over creating individual files like user.service.js and importing service functions separately?
There is nothing wrong with your alternative solution; choose the one that best fits your business logic and it is clearer to your team.
In this case, we demoed the autoload feature and put the accent on the loading order.
Creating the user.service.js
works, but it is needed to take care of the loading order or you may hit some undefined
issue during the start-up phase.
Does extensively decorating the fastify instance impact performance?
It does, but it is not an issue unless we add A LOT (1000?) of props. Defining a decorator adds a property to the Fastify prototype, that is not a heavy operation.
Does adding all service functions on each request affect performance?
It may affect performance. We define the decorator to add to the request prototype the todosDataSource
prop and then the hook assigns to the prop an object with some functions, so if we measure the performance drop here is:
request.todosDataSource = { ...
)So any application's bottlenecks can't hide in these basic JS operation.
Is there a more efficient way to handle this?
Yes, of course. If we ask ourselves, what does this code do? It adds a utility to our request
object.
Does my handler need these utilities? If the answer is not, the code we are running is useless and you may change the request
decorator object to a set of functions:
fastify.decorateRequest('countTodos', (filter = {}) => {
filter.userId = this.user.id // [4]
const totalCount = await todos.countDocuments(filter)
return totalCount
})
// etc...
In this case, the request prototype will be bigger, but the utility functions are there and ready to use without the need for a hook
function.
Here is the game: find the best suite for the application and the dev team, fastify will adapt 👍🏼
Hi there, I've been really enjoying the Fastify book on O'Reilly! The complete guide for the todo app has been fantastic for managing code. I do have a couple of questions:
Usage of
fastify.decorate
in autoHooks: In the autoHooks files, we're usingfastify.decorate('usersDataSource', {})
. Why was this approach chosen over creating individual files likeuser.service.js
and importing service functions separately? Does extensively decorating the fastify instance impact performance?onRequest
hook in autoHooks for todos routes: We're adding service functions torequest.todoDataSource
in theonRequest
hook. For instance:fastify.addHook('onRequest', async function (request, reply) { request.todosDataSource = { async countTodos(filter = {}) { filter.userId = request.user.id const totalCount = await todos.countDocuments(filter) return totalCount }, // ...other functions } })