网关中间件

Gateway middlewares works almost same as route middlewares. Middleware is a function, which is called before gateway message subscriber. Gateways middleware functions have access to native socket object. They can be something like a barrier - if middleware function does not call next(), the message will never be handled by subscriber.

网关中间件和路由中间件的工作原理几乎一致。中间件是一个函数,该函数在网关消息被订户处理之前调用。网关中间件函数可以访问本地scoket对象。所以它可以被看作是消息和订户中间的屏障---如果中间件函数不调用next()方法,消息将不会送达到订户那里。

Example:

@Middleware()
export class AuthMiddleware implements GatewayMiddleware {
    public resolve(): (socket, next) => void {
        return (socket, next) => {
            console.log('Authorization...');
            next();
        };
    }
}

Some facts about gateway middlewares:

  • you should use @Middleware() annotation to tell Nest, that this class is a middleware,
  • you can use GatewayMiddleware interface, which forces on you to implement resolve() method,
  • middlewares (same as components) can inject dependencies through their constructor (dependencies have to be a part of module),
  • middlewares must have resolve() method, which must return another function (higher order function).

网关中间件的实际情况:

  • 使用@Middleware()注释告诉Nest,这个类是一个中间件。
  • 可以使用NestMiddleware界面,这会迫使你执行resolve()方法。
  • 中间件(如组件一样)可以通过构造函数注入依赖(依赖必须是模块的一部分)。
  • 中间件必须有resolve()方法,该方法必须返回另一个函数(高阶函数)。

Okey, we already have prepared middleware, but we are not using it anywhere. Let's set it up:

好了,中间件已经准备就绪,但是还没有投入到使用中,不过我们还是按照如下方式先设置好中间件待用:

@WebSocketGateway({
    port: 2000,
    middlewares: [ ChatMiddleware ],
})
export class ChatGateway {}

As shown, @WebSocketGateway() accepts additional metadata property - middlewares, which is an array of middlewares. Those middlewares will be called before message handlers.

如上所示,@WebSocketGateway()接受额外的元数据属性--middlewaresmiddlewares是一个中间件数组。这个中间件数组在消息处理程序之前被调用。

results matching ""

    No results matching ""