schmervice icon indicating copy to clipboard operation
schmervice copied to clipboard

Usage with other plugins.

Open vishnu-wednesday opened this issue 4 years ago • 1 comments

Hi @devinivy,

I am trying to use schmervice with another plugin. I have directory-based routing with wurst. https://github.com/felixheck/wurst

I register schmervice as

  await server.register(Schmervice);

    server.registerService(
        class MathService extends Schmervice.Service {
            add(x, y) {
                this.server.log(['math-service'], 'Adding');

                return Number(x) + Number(y);
            }

            multiply(x, y) {
                this.server.log(['math-service'], 'Multiplying');

                return Number(x) * Number(y);
            }
        }
    );


   await server.register({
        plugin: wurst,
        options: {
            routes: '**/routes.js',
            cwd: path.join(__dirname, 'lib/routes'),
            log: true
        }
    });

in a routes folder, when I look at request.services(). It is an empty object. How do I register Schmervice with another plugin so that I get access to the service in my route?

PS: sorry for the tag!

vishnu-wednesday avatar Oct 21 '21 06:10 vishnu-wednesday

Hi! The issue here relates to schmervice's idea of namespaces. In short, by default routes will be able to see the services registered in the same plugin that the routes were defined in: schmervice enforces plugin boundaries. There's some more information about this in the docs if you search around for references to "namespace." https://hapipal.com/docs/schmervice#serverservicesnamespace

In your setup, your routes are actually registered by wurst. So from a namespacing perspective your routes belong to the wurst plugin and your services belong to your application— these cross a plugin boundary, so the services don't appear in request.services() for routes registered by wurst. There are two ways to fix this:

  1. Pass request.services(true) in order to circumvent the plugin boundary. If your services are registered within a plugin named 'my-app' you could also be more specific and pass request.services('my-app').
  2. Or use a tool other than wurst for registering the routes in that directory. Often in hapi pal applications we use haute-couture, which would register your routes in the same plugin as your services and there would be no plugin boundary between them.

Hope this helps!

devinivy avatar Oct 21 '21 12:10 devinivy