trailsjs / trails

:evergreen_tree: Modern Web Application Framework for Node.js.
http://trailsjs.io
Other
1.67k stars 70 forks source link

Service init/unload methods #290

Open patrickd- opened 7 years ago

patrickd- commented 7 years ago

Issue Description

Looking at the Service API (https://trailsjs.io/doc/en/ref/service) I was a bit surprised to see there are no initialize() and unload() methods. Services are singleton instances intended to do the applications heavy lifting right? I had expected the possibility to eg. block the applications start until my Service has connected to a different service. At the moment it would always be necessary to write a trailpack when the service would require any form of bootup and shutdown logic.

Is this an intended design decision? (If not,) would you be open to change that?

Environment

jaumard commented 7 years ago

You're right for now the services can't block the project to start and that was the plan I think and currently you're force to do it with trailpack (but it can be done locally and easily). But I think it should be a nice improvement to have an initialize and unload for services. What the @trailsjs/maintainers think about this ?

For now you need to create a trailpack or use trailpack-bootstrap to initialize services but it didn't block the project to start

tjwebb commented 7 years ago

I had expected the possibility to eg. block the applications start until my Service has connected to a different service. At the moment it would always be necessary to write a trailpack when the service would require any form of bootup and shutdown logic.

Sort of; Trails v2 has a bug in its config merging logic that makes the developer unable to properly override trailpack configs, but in Trails v3 the mechanism for accomplishing this is as follows:

  1. Once your Service has satisfied its own preconditions, fire an event. This logic would go in the constructor of the Service, which you can override like so:
constructor (app) {
  super(app)
  // ... custom stuff
  this.app.emit('MyService:ready')
  1. Add this event MyService:ready as a precondition for some trailpack, e.g. trailpack-hapi, so that the trailpack does not load until your Service is ready. This is accomplished by adding an item to the trailpack's config.lifecycle.listen. e.g.
    // config/trailpacks.js
    module.exports = {
    hapi: {
      lifecycle: {
        listen: [
          'MyService:ready'
        ]
      }
    }
    }

This will ensure that trails will complete its startup process only when both the Service and the trailpack are done. But, like I said, this will not currently work in Trails v2.

If your Service constructor logic relies on some particular Trailpack to be loaded, then you'll want to specifically listen for that trailpack's initialized event first. e.g.

this.app.on('trailpack:foobar:initialized', () => {
  // init logic