Apollo Server Express:请求实体太大



我需要在 GraphQL 突变中发布一个大有效载荷。如何增加阿波罗服务器的机身尺寸限制?

我使用的是apollo-server-express2.9.3 版。

我的代码(简体(:

const myGraphQLSchema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
user: UserQuery,
},
}),
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: () => ({
...UserMutations,
}),
}),
});
const apolloServer = new ApolloServer(schema: myGraphQLSchema);
const app = express();
app.use(apolloServer.getMiddleware({ path: '/graphql' });

不确定它是在哪个版本中添加的,但在 2.9.15 上,您可以在 applyMiddleware 函数中应用它。

const apolloServer = new ApolloServer(someConfig);
apolloServer.applyMiddleware({
app,
cors: {
origin: true,
credentials: true,
},
bodyParserConfig: {
limit:"10mb"
}
});

只需在 Apollo 服务器中间件之前添加一个 Express 体解析器:

import { json } from 'express';
app.use(json({ limit: '2mb' });
app.use(apolloServer.getMiddleware({ path: '/graphql' });

如果你想花哨,你可以对经过身份验证的请求和未经身份验证的请求设置单独的正文大小限制:

const jsonParsers = [
json({ limit: '16kb' }),
json({ limit: '2mb' }),
];
function parseJsonSmart(req: Request, res: Response, next: NextFunction) {
// How exactly you do auth depends on your app
const isAuthenticated = req.context.isAuthenticated();
return jsonParsers[isAuthenticated ? 1 : 0](req, res, next);
}
app.use(parseJsonSmart);
app.use(apolloServer.getMiddleware({ path: '/graphql' });

最新更新