Apollo Server Express:请求实体太大

Mar*_*cek 6 express apollo graphql apollo-server

我需要在 GraphQL 突变中发布大量有效负载。如何提高 Apollo Server 的主体大小限制?

我使用的是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' });
Run Code Online (Sandbox Code Playgroud)

Max*_*ain 8

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

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


Mar*_*cek 7

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

import { json } from 'express';

app.use(json({ limit: '2mb' });
app.use(apolloServer.getMiddleware({ path: '/graphql' });
Run Code Online (Sandbox Code Playgroud)

如果您想变得更奇特,您可以为经过身份验证的请求和未经身份验证的请求设置单独的正文大小限制:

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' });
Run Code Online (Sandbox Code Playgroud)