Skip to content

Long running boot scripts may break the sequence of mounting middleware. #1016

Description

@ih2502mk

Just pointing this out here in case someone encounters similar issue.

In a server.js file, that normally gets generated by slc loopback there is a set of middleware mounted on the app like this:

app.use(loopback.favicon());
app.use(loopback.compress());

boot(app, __dirname); 

app.use(loopback.urlNotFound());
app.use(loopback.errorHandler());

app.start = function() {
  return app.listen(function() {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));    
  });
};

if (require.main === module) {
  app.start();
}

The problem that I've encountered happens when I have some long running asynchronous boot script in my ./boot directory. The actual reason I believe is my boot script process.nextTick()ing its callback. I'm not using process.nextTick() directly but some module that I use — does.

What happens is while boot() function is doing its thing server.js goes on further and mounts loopback.urlNotFound() and loopback.errorHandler() prior to mounting whatever else should get mounted in other boot scripts.

boot() function accepts a callback and also makes app emit 'booted' event reliably once boot scripts finish. One of the solutions is to use 'booted' event on the app object like this:

app.use(loopback.favicon());
app.use(loopback.compress());

boot(app, __dirname); 

app.once('booted', function() {

  app.use(loopback.urlNotFound());
  app.use(loopback.errorHandler());

  app.start = function() {
    return app.listen(function() {
      app.emit('started');
      console.log('Web server listening at: %s', app.get('url'));    
    });
  };

  if (require.main === module) {
    app.start();
  }
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions