पाठ 15 / 32

Encapsulation और Scope

Modular, conflict-free apps बनाने के लिए hooks, decorators और routes को plugins के भीतर scoped रखें।

Plugin scope isolation

एक plugin के अंदर registered plugins उस plugin के लिए scoped होते हैं। Decorators, hooks, और routes sibling plugins में leak नहीं होते।

Nested plugins

एक plugin को register करके sub-apps बनाएँ जो child plugins को register करता है।

// routes/v1.js
export default async function v1Routes(fastify, opts) {
  fastify.get('/health', async () => ({ version: '1' }));
}

// routes/v2.js
export default async function v2Routes(fastify, opts) {
  fastify.get('/health', async () => ({ version: '2' }));
}

// server.js
fastify.register(v1Routes, { prefix: '/v1' });
fastify.register(v2Routes, { prefix: '/v2' });
// GET /v1/health -> { version: '1' }
// GET /v2/health -> { version: '2' }

Decorators अपने plugin के अंदर रहते हैं

हर register एक child context बनाता है।

  • child में decorate parent को नहीं दिखता।
  • ऊपर share करना हो तो fastify-plugin से wrap करें।
const fastify = require('fastify')();

fastify.register(async (child) => {
  child.decorate('secret', 42);
  console.log('child', child.secret);
});

fastify.ready().then(() => {
  console.log('parent', fastify.secret);
});

Output:

child 42
parent undefined

त्वरित जाँच

त्वरित जाँच: plugin का decorator parent instance को दिखाने के लिए क्या करें?

  • plugin का नाम `global` रखें
  • इसे `fastify-plugin` से wrap करें
  • `decorate` दो बार call करें
Answer

इसे `fastify-plugin` से wrap करें — `fastify-plugin` encapsulation हटा देता है, इसलिए decorators और hooks parent पर लागू होते हैं।