Search code examples
node.jsexpressmiddleware

How to pass data to next middleware function in NodeJS


I'm writing my own implementation of middleware for a socket system. I've read through the source code of Laravel's middleware and some documentation on ExpressJS's implementation for inspiration.

However, I'm getting stuck on passing the data from one middleware handler to another.

I wrote a very basic example below. The output should be 4 but I don't know how to pass the output from one handler to the other. I'm guessing by setting a temporary variable, but I'm not sure how performant that is.

let each = require('lodash/each')
class Middleware {
  constructor() {
    this.handlers = [
      function (data) {return data + 1},
      function (data) {return data + 2}
    ]
  }
}

class Router {
  constructor() {
    this.middleware = new Middleware
  }
  route(data) {
    each(this.middleware.handlers, function(handler) {
      handler(data) // no idea what to do here
    })
  }
}


class Socket {
  constructor() {
    this.router = new Router
  }
  write(data) {
    return this.router.route(data)
  }
}

let router = new Router

console.log(socket.write(1)) // should be 4

Solution

  • Change the route function inside Router class as following and the result of socket.write(1) will be 4:

    class Router {
        constructor() {
            this.middleware = new Middleware
        }
        route(data) {
            each(this.middleware.handlers, function (handler) {
                data = handler(data)
            })
            return data
        }
    }