我无法在 ApolloServer 实例上使用上下文,我得到 TS2353:对象文字只能指定已知属性,并且 ApolloServerOptionsWithSchema 类型中不存在上下文
我尝试过制作自定义 Context 接口并将其传入,但效果不佳
这是代码:
import { ApolloServer } from '@apollo/server';
import { typeDefs } from './schema/type-defs';
import { resolvers } from './schema/resolvers';
import { createServer } from 'http';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import express from 'express';
import { BaseContext } from "@apollo/server";
import {expressMiddleware} from "@apollo/server/express4";
import bodyParser from 'body-parser';
const app = express();
// This `app` is the returned value from `express()`.
const httpServer = createServer(app);
const schema = makeExecutableSchema(
{ typeDefs, resolvers }
);
const wsServer = new WebSocketServer({
server: httpServer,
path: '/graphql',
});
const serverCleanup = useServer({ schema }, wsServer);
const server = new ApolloServer<BaseContext>({ // Specify generic type here
schema,
context: ({ req, res })=> {
return { req, res };
},
plugins: [ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
},
};
},
}
],
});
(async () => {
await server.start()
httpServer.listen(4000, () => {
console.log(`Query endpoint ready at http://localhost:4000/graphql`);
console.log(`Subscription endpoint ready at ws://localhost:4000/subscriptions`);
});
app.use('/graphql', bodyParser.json(), expressMiddleware(server));
})();
您可能正在使用 Apollo 服务器 v4,但正在阅读引用 v3 的文档。两者的
context
的用法有很大不同。
在 v4 中
context
是 startStandAloneServer
函数的一个选项:
const server = new ApolloServer({ typeDefs, resolvers});
startStandaloneServer(server, { context })
我也有同样的问题。对我有用的是通过expressMiddleware 函数传递上下文:
app.use(
"/graphql",
cors<cors.CorsRequest>(),
bodyParser.json(),
expressMiddleware(server, {
context: ({ req , res }) => {
return { req, res };
},
})
);