首页 > 解决方案 > 如何在 localhost 中使用 apollo graphql 进行 fastify 会话

问题描述

您好,我想使用 apollo graphql 设置 fastify 会话,当我想访问会话时出现此错误:“消息”:“无法读取未定义的属性‘会话’”

我不知道它是否在生产模式下工作。

我的快递也有同样的问题。

索引.ts

import { ApolloServer } from "apollo-server-fastify";
import { ApolloServerPluginDrainHttpServer } from "apollo-server-core";
import fastify, { FastifyInstance } from "fastify";
import { ApolloServerPlugin } from "apollo-server-plugin-base";
import fastifySession from "fastify-session";
import fastifyCookie from "fastify-cookie";
import { typeDefs } from "./schema";
import testResolver from "./testResolver";
function fastifyAppClosePlugin(app: FastifyInstance): ApolloServerPlugin {
  return {
    async serverWillStart() {
      return {
        async drainServer() {
          await app.close();
        },
      };
    },
  };
}
const app = fastify();
app.register(fastifyCookie);
app.register(fastifySession, {
  secret:
    "secret",
  saveUninitialized: false,
  cookie: {
    httpOnly: true,
    secure: false,
  },
});
const server = new ApolloServer({
  typeDefs,
  resolvers: testResolver,
  context: ({ req }) => {
    return { session: req.session };
  },
  plugins: [
    fastifyAppClosePlugin(app),
    ApolloServerPluginDrainHttpServer({ httpServer: app.server }),
  ],
});
server.start().then(() => {
  app.register(server.createHandler());
  app.listen(4000).then(() => {
    console.log(
      ` Server ready at http://localhost:4000${server.graphqlPath}`
    );
  });
});

解析器:

import { IResolvers } from "@graphql-tools/utils";
const testResolver: IResolvers = {
  Query: {
    test: (_, args, { session }, info) => {
      session.data = "dick";
      return true;
    },
  },
  Mutation: {
    testMut: (_, args, { session }, info) => {
      console.log(session.data);
      return true;
    },
  },
};
export default testResolver;

标签: graphqlapolloapollo-serverfastifyfastify-cookie

解决方案


推荐阅读