Advanced Customization with Fastify.js Decorators
Advanced Customization with Fastify.js Decorators
What are Fastify.js Decorators?
Fastify.js is one of the high-performance Node.js frameworks and allows you to easily customize on it. One of the most powerful ways of this customization is the concept of decorators. With Fastify.js decorators, you can add your own functions or properties to your application and easily use them in all handlers or plug-ins. Thanks to Fastify.js decorators, code repetition is reduced in your projects and a modular structure is created.
Using Fastify Decorators
With the decorator structure in Fastify.js, you can easily access, for example, global helper functions or services. You can add decorators with functions such as decorate or decorateRequest. Basically, you can define your own properties on the Fastify instance or on the request/response objects.
Example: Adding a New Decorator
const fastify = require('fastify')();
fastify.decorate('toUpperCase', function(str) {
return str.toUpperCase();
});
fastify.get('/', (request, reply) => {
const mesaj = fastify.toUpperCase('merhaba fastify.js decorators!');
reply.send({ sonuc: mesaj });
});
fastify.listen({ port: 3000 }, (err) => {
if (err) throw err;
console.log('Fastify.js Decorators example started.');
});
In the example above, a function named toUpperCase is added to the Fastify instance and can be used directly inside the route handler.
Adding a Decorator to the Request
Sometimes, you may want to add functions specific only to incoming requests. For this, you can use the decorateRequest function:
fastify.decorateRequest('karsila', function() {
return 'Welcome!';
});
fastify.get('/hosgeldin', (request, reply) => {
reply.send({ mesaj: request.karsila() });
});
Here, the karsila function has been added only to the request object.
Benefits and Things to Consider with Fastify.js Decorators
There are some advantages to using Fastify.js decorators: Reducing code repetition, enabling dependency injection, and increasing the testability of the application. However, trying to add a property that does not exist again will throw an error. Therefore, it is good practice to check for the existence of a property before adding a decorator each time.
Conclusion
Fastify.js decorators make your work much easier in large and modular Node.js projects. You can define both global helpers and request-specific properties. With the "Fastify.js decorators" keyword, you should definitely explore this structure to improve your code quality in future projects.

Yorum Gönder