Don’t repeat yourself
Defining the application logic inside routes is fine for simple applications such as the one in our example. In a real-world scenario, though, when we need to use our logic across an application in multiple routes, it would be nice to define that logic only once and reuse it in different places. So, once more, Fastify has us covered.
We can expand our autohooks.cjs
plugin by adding what is commonly known as a data source. In the following snippet, we expand the previous plugin, adding the needed code, although, for the brevity of the exposition, we are showing only the function for the createTodo
handler; you can find the whole implementation inside the book’s code repository:
'use strict' const fp = require('fastify-plugin') const schemas = require('./schemas/loader') module.exports = fp(async function todoAutoHooks (fastify, opts) { // [1] const todos = fastify.mongo.db.collection('todos&apos...