无法从上下文访问请求

Can't access req from context

我正在使用 Koa.js 和 Apollo Server 的 apollo-server-koa

我调试了 { req } 并且值未定义。 我已经按照文档进行操作,但仍然没有任何线索。 即使我访问 req.headers.authorization 并将其放在 graphql gui 的 HTTP Header 上:

{
  "authorization": "bla"
}

该值仍然是 undefined

app.ts:

import cors from "@koa/cors";
import Koa from "koa";

import config from "./config/environtment";
import server from "./server";

const PORT: number = config.port;

async function bootstrap() {
  try {
    const app: Koa = new Koa();

    server.applyMiddleware({ app });

    app
      .use(cors())
      .listen(PORT, () =>
        console.log(
          `Server running on http://localhost:${PORT}${server.graphqlPath}`,
        ),
      );
  } catch (error) {
    console.error(error);
  }
}

bootstrap();

server.ts:

import { ApolloServer } from "apollo-server-koa";

import typeDefs from "./graphql/schema";
import resolvers from "./graphql/resolvers";
import context from "./graphql/context";

export default new ApolloServer({
  typeDefs,
  resolvers,
  context,
});

context.ts

export default ({ req }) => {
  console.log(req) // return undefined.
  return {
    test: "test",
  };
};

文档特定于 apollo-server,它在后台使用 apollo-server-express。我相信对于 apollo-server-koa,选项是在一个包含 Koa Contextctx 字段的对象中传递的。所以以下应该有效:

export default ({ ctx }) => {
  console.log(ctx.request)
  console.log(ctx.response)
  return {};
};