Skip to content

Service Middleware Considerations

Francisco Ruiz edited this page Aug 25, 2024 · 1 revision

Service Middleware considerations

Within a middleware, you can use the container to access the registered services. This enables you to have full control for implementing the necessary logic in your global middleware, but there is one limitation. If you call the same service that the middleware is using, it will result in an infinite loop within your middleware.

container.middleware.add('KeyService1', (next, context, args) => {
  const { container } = context;

  // Get the services 
  const service1 = container.get('KeyService1');
  const service2 = container.get('KeyService2');

  // Infinite loop error (KeyService1)
  const random = service1.getRandom();

  // Calling a method or function from any other service, will not
  // generate an infinite loop.
  const uniqId = service2.getUniqId();
  return next(args);
})

To avoid the infinite loop, you can use the proxyMiddleware option to disable the middleware proxy:

container.middleware.add('KeyService1', (next, context, args) => {
  const { container } = context;

  // Get the services
  const service1 = container.get('KeyService1', {
    proxyMiddleware: false,
  });
  const service2 = container.get('KeyService2');

  // Now we can use the service1 without the infinite loop
  const random = service1.getRandom();
  const uniqId = service2.getUniqId();

  return next(args);
})

1. Getting Started

2. Core Concepts

3. Middleware

4. Caching and Memoization

5. Typescript

6. Considerations

7. API Reference

8. Examples and Use Cases

9. Contributing

We welcome contributions from the community! Whether it's reporting a bug, suggesting a feature, or contributing code, your involvement is key to making Packet.js better. Please check out this section for more details.

10. Support

If you encounter any issues or bugs while using packetjs, or if you have any feature requests, please feel free to open an issue in our GitHub repository. You can report issues, track progress, and engage in discussions with the community via the following link:

11. FAQ

If you have any questions or need further assistance, feel free to reach out via the discussion board.

12. License

Clone this wiki locally