# Encapsulation और Scope — Fastify: High-Performance Node.js APIs बनाना

Source: https://www.skillbyai.com/hi/fastify/ff-encapsulation

> 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 करता है।

```javascript
// 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 करें।

```js
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
```

त्वरित जाँच

**Quiz:** plugin का decorator parent instance को दिखाने के लिए क्या करें?

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

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