Koa, Node.js, Server - 如何从Server对象中获取Koa的Router级中间件功能?

Koa, Node.js, Server - How can I get Koa's Router-level middleware function from the Server object?

我想从我在代码中最后创建的 server 对象调用 middleware 函数。我怎样才能做到这一点?似乎那里没有很多信息。我的目标是提取中间件函数并为所有调用保留一个索引。当我测试应用程序时,我不必通过 http 请求实际调用。

const app = new Koa();
  const router = new Router();

  async function middleware(context: Koa.Context) {
    // the client is requesting a specific statusCode to be returned
    if (context.query.status !== undefined) {
      context.status = parseInt(context.query.status, 10);
      if (context.query.body !== undefined) {
        try {
          context.body = JSON.parse(context.query.body);
        } catch (e) {
          context.body = context.query.body;
        }
      }
      return;
    }
    // put all the inbound x-headers in the response, prepended with 'ping.'
    Object.keys(context.headers).forEach(header => {
      if (header.toLowerCase().startsWith('x-')) {
        context.response.set(`x-ping-${header.slice(2)}`, context.headers[header]);
      }
    });

    context.body = {
      ping: (context.request as any).body
    };
    context.status = 200;
  }
  router.head('/ping', middleware);
  router.get('/ping', middleware);
  router.del('/ping', middleware);
  router.put('/ping', middleware);
  router.post('/ping', middleware);
  router.patch('/ping', middleware);

  app.use(koaBody());
  app.use(router.routes());
  app.use(router.allowedMethods());

  const port = await findPort();
  const server = app.listen(port);

以下是一些可能有助于解决此问题的日志。 console.log(服务器):

Server {
  domain: null,
  _events: 
   { request: [Function: handleRequest],
     connection: [ [Function: connectionListener], [Function] ] },
  _eventsCount: 2,
  _maxListeners: undefined,
  _connections: 0,
  _handle: 
   TCP {
     reading: false,
     owner: [Circular],
     onread: null,
     onconnection: [Function] },
  _usingWorkers: false,
  _workers: [],
  _unref: false,
  allowHalfOpen: true,
  pauseOnConnect: false,
  httpAllowHalfOpen: false,
  timeout: 120000,
  keepAliveTimeout: 5000,
  _pendingResponseData: 0,
  maxHeadersCount: null,
  _connectionKey: '6::::49612',
  [Symbol(IncomingMessage)]: 
   { [Function: IncomingMessage]
     super_: 
      { [Function: Readable]
        ReadableState: [Function: ReadableState],
        super_: [Function],
        _fromList: [Function: fromList] } },
  [Symbol(ServerResponse)]: { [Function: ServerResponse] super_: { [Function: OutgoingMessage] super_: [Function] } },
  [Symbol(asyncId)]: 3220 }

我明白了。为了在测试中间件时不使用服务器,需要使用app.callback().

代码预览:

 const socket: net.Socket = new net.Socket();
 const req = new http.IncomingMessage(socket);
 req.url = url;
 req.method = method;
 req.headers = headers; // (whatever more you need to set)

 if (json) {
     (req as any).body = json;
 }
 const res = new http.ServerResponse(req);
 const cb = callback(app);
 try {
     response = (await cb(req, res));
      (...)