chrisdavies/rlite

Middleware support

Closed this issue · 1 comments

Is there any way to easily use middleware with rlite, i do i have do add the method call in each of the callbacks?

It's not baked in, but it's pretty simple to wrap Rlite with middleware, depending on your needs. Here's a middleware that prepends a hello message onto all Rlite results (using Rlite 2.x).

function myMiddleware(router) {
  return function (url) {
    return 'HELLO FROM MY MIDDLEWARE ' + router(url);
  };
}

const route = myMiddleware(rlite(notFound, {
  // Default route
  '': function () {
    return 'Home';
  },

  // #inbox
  'inbox': function () {
    return 'Inbox';
  },

}));

// logs HELLO FROM MY MIDDLEWARE Inbox
console.log(route('inbox'));

Also, routes can return anything (objects, strings, etc.). In my case, I generally have mine simply return React or preact components which I then render. But you could have them return objects of a certain shape, say: {view: '<h1>hi</h1>', status: 200}. This would allow a wrapper like the one above to know more about the result, if necessary.