Skip to content

Integrate phases with boot(...) #46

Closed

Activity

  1. added this to the #Epic: Component milestone on Oct 7, 2014
  2. raymondfeng commented on Oct 7, 2014

    @raymondfeng
    Member

    Let's borrow some ideas from JAX-RS:

    https://jersey.java.net/documentation/latest/filters-and-interceptors.html

    In particular:

    • Types of phases (middleware, remoting, model, connector)
    • Predefined phases
    • Execution order
    • Binding of handlers (global/name binding/dynamic binding)
  3. ritch commented on Oct 7, 2014

    @ritch
    MemberAuthor

    @raymondfeng here is the code scratch pad we used to pair program some of the basic implementation ideas.

    var loopback = require('loopback');
    var boot = require('loopback-boot');
    
    var app = module.exports = loopback();
    
    // Set up the /favicon.ico
    app.use(loopback.favicon());
    
    // request pre-processing middleware
    app.use(loopback.compress());
    
    // -- Add your pre-processing middleware here --
    
    // boot scripts mount components like REST API
    boot(app, __dirname);
    
    var root = app.createPhase('root');
    
    foreach(phase in config.phases) {
    
    }
    
    foreach(phase in app.phases()) {
      foreach(handler in handlersForGivenPhase) {
        app.register(phase.name, hander)
      }
    
      root.add(phase);
    }
    
    // juggler
    User.create = function(data, cb) {
      User.SOMETHING.execPhase('validate', function() {
        // the validate phase!
        // ... and so on...
      });
    }
    
    // hook into your method
    Phase.wrapSync('yourMethod', ...);
    
    MyModel.register('beforeYourMethod', function(ctx) {
      ctx.arguments
    })
    
    MyModel.yourMethod = function proxy() {
      // executes concrete yourMethod
      // before phase
      // if sync
      //  executes the after phase
      // async
      //   wrap the callback
      //      exec the after phase
    }
    
    Model.wrap = function(methodName, options) {
      var methodPhase = Model.createPhase(key);
      model[methodName] = function() {
        var args = arguments;
        if(isSync) {
          methodPhase.add('before', methodName, function() {
            originalMethod(args);
            methodPhase.add('after', methodName);
          });
        } else {
          var cb = getCb(args);
          methodPhase.add('before', ..., function() {
            methodPhase.add('after', methodName);
          });
        }
      }
    }
    
    app.register('foo:*', function(cb) {
      console.log(ctx.phase.name);
      cb();
    });
    
    MyModel.register('afterYourMethod', function(ctx) {
      ctx.arguments
    })
    
    app.models.User.register('validate', function(ctx, done) {
      done(new Error('nothing is valid!'));
    });
    
    // new imp for enable auth
    app.register('auth', function(ctx) {
      // ...
      loopback.Context
      ctx.remotingContext.req
    });
    
    var explorer;
    try {
      explorer = require('loopback-explorer');
    } catch(err) {
      console.log(
        'Run `npm install loopback-explorer` to enable the LoopBack explorer'
      );
      return;
    }
    
    var restApiRoot = server.get('restApiRoot');
    
    var explorerApp = explorer(server, { basePath: restApiRoot });
    server.use('/explorer', explorerApp);
    server.once('started', function() {
      var baseUrl = server.get('url').replace(/\/$/, '');
      // express 4.x (loopback 2.x) uses `mountpath`
      // express 3.x (loopback 1.x) uses `route`
      var explorerPath = explorerApp.mountpath || explorerApp.route;
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
    });
    
    var restApiRoot = server.get('restApiRoot');
    server.use(restApiRoot, server.loopback.rest());
    
    // -- Mount static files here--
    // All static middleware should be registered at the end, as all requests
    // passing the static middleware are hitting the file system
    // Example:
    //   app.use(loopback.static(path.resolve(__dirname', '../client')));
    var websitePath = require('path').resolve(__dirname, '../client');
    app.use(loopback.static(websitePath));
    
    // Requests that get this far won't be handled
    // by any middleware. Convert them into a 404 error
    // that will be handled later down the chain.
    app.use(loopback.urlNotFound());
    
    // The ultimate error handler.
    app.use(loopback.errorHandler());
    
    app.start = function() {
      // start the web server
      return app.listen(function() {
        app.emit('started');
        console.log('Web server listening at: %s', app.get('url'));
      });
    };
    
    // start the server if `$ node server.js`
    if (require.main === module) {
      app.start();
    }
  4. assigned and unassigned on Oct 7, 2014
  5. bajtos commented on Oct 9, 2014

    @bajtos
    Member

    I have reviewed the code from the scratchpad. Few comments:

    • I find the names of the new methods little bit confusing, we should come up with a more descriptive name (e.g. onPhase(name, fn) instead of register(name, fn))
    • app.createPhase and root.add(phase) seem rather arbitrary to me, I don't understand what is the purpose. It's not a problem, I am just saying that I cannot asses this part.
    • The proposal does not handle phase ordering, nor Binding of handlers (global/name binding/dynamic binding)

    Other than that, this looks like a sensible approach to me.

    It would be great if we can build this incrementally in small steps. Start with something small yet complete, then add more stuff building on top of that. Perhaps start by replacing beforeValidate and afterValidate hooks with the new implementation?

    I don't understand what is the relation of this feature with the middleware registration and ordering, if there is any relation. In particular, how will be phase.toMiddleware() mounted on the app?

  6. 57 remaining items

  7. dhmlau commented on Aug 23, 2018

    @dhmlau
    Member

    Since the last comment was almost 4 years ago, closing due to inactivity. Please create a new issue if you are still running into problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions