Next JS 服务器端 graphql 订阅

Next JS server side graphql subscriptions

我目前正在使用 Next JS 构建聊天应用程序。我在前端使用 graphql 和 Apollo Client,在后端使用 Apollo Server。现在我想要实时更新,但我发现 不支持 apollo-server-micro 中的订阅。正如他们在这里写的那样: https://www.apollographql.com/docs/apollo-server/data/subscriptions#enabling-subscriptions

Beginning in Apollo Server 3, subscriptions are not supported by the "batteries-included" apollo-server package. To enable subscriptions, you must first swap to the apollo-server-express package (or any other Apollo Server integration package that supports subscriptions).

但我不能使用 apollo-server-express,因为我使用 NextAuth 进行身份验证,然后将其传递给上下文:

export async function createContext({
  req,
  res,
}: {
  req: NextApiRequest;
  res: NextApiResponse;
}): Promise<Context> {
  const session = await getSession({ req });
  const user = { ...session?.user, _id: session?.userId } as User;
  const db = await dbConnect();
  return {
    user,
    db,
  };
}

感谢您的帮助。

我找到了一个解决方案,适合所有想在服务器上使用 graphql 订阅 的人:
使用 graphql-yoga 而不是: https://www.graphql-yoga.com/docs/features/subscriptions

我的 pages/api/graphql.ts 代码:

import { createServer, createPubSub, PubSub } from "@graphql-yoga/node";
import { NextApiRequest, NextApiResponse } from "next";
import { Session } from "next-auth";
import { getSession } from "next-auth/react";

const pubSub = createPubSub<{
  "user:newMessage": [userId: string, message: Message];
  "user:newChat": [userId: string, chat: Chat];
}>();

export type pubSub = typeof pubSub;

const server = createServer<
  {
    req: NextApiRequest;
    res: NextApiResponse;
  },
  {
    user: User;
    pubSub: any;
  }           
>({
  context: async ({ req }) => {
    const session = await getSession({ req });
    await dbConnect();
    return {
      user: { ...session?.user, _id: session?.userId } as User,
      pubSub,
    };
  },
  schema: {
    typeDefs,
    resolvers: {
      Query,
      Mutation,
      Subscription,
    },
  },
});

export default server;