ZijianHe / koa-router

Router middleware for koa.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: Can I fetch the Router-level middleware function from the Server object (application level)

gatsbyz opened this issue · comments

I want to get the call to middleware function from the server object that I create last in the code. How can I achieve that? It seems like there is not a lot of information out there. My goal is to extract the middleware functions and keep a index for all the calls. When I test the application, I do not have to actually call through the http requests.

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);

I'm not sure what you're asking. This section of github is typically reserved for logging issues with the library itself—that is, when it does not do what it says it does. It seems like your question is more about how to architect a solution to your problem. I suggest posting this question on Stack Overflow in order to find help with the above code.

If you believe there to be an error in the library affecting your code, please reopen this issue and use the issue template to answer the necessary questions.