如何向 graphql createHandler 方法添加自定义 HTTP 响应?

问题描述 投票:0回答:1

即使出现错误,GraphQl 也会返回 200,但响应中包含错误对象。 我想把它设置为400。 假设我需要将它集成到 createHandler 中?

import { createHandler } from "graphql-http/lib/use/express";
import mySchema from "./.mySchema";

const StringArrayScalar = new GraphQLScalarType({......

var root = {
    query1({ id }) {
        return xxx
    },
    query2({ id }) {
        return xxx
    },
};

const handler = createHandler({
    schema: mySchema,
    rootValue: root,
    pretty: true,
    graphiql: true,
    resolver: {
        StringArray: StringArrayScalar,
    }
});

export default handler;
node.js express graphql httpresponse express-graphql
1个回答
0
投票
import { createHandler } from "graphql-http/lib/use/express";
import mySchema from "./.mySchema";

const StringArrayScalar = new GraphQLScalarType({......

var root = {
    query1({ id }) {
        return xxx
    },
    query2({ id }) {
        return xxx
    },
};

const handler = createHandler({
    schema: mySchema,
    rootValue: root,
    pretty: true,
    graphiql: true,
    resolver: {
        StringArray: StringArrayScalar,
    },
    responseCallback: (req, res, params) => {
      const { status, headers, data } = params;
      if (data.errors && data.errors.length > 0) {
        return { status: 400, headers, data };
      }
      return { status, headers, data };
    },
});

export default handler;

每当响应中有错误时,都会以

400 Bad Request
进行响应,否则默认为 200。

© www.soinside.com 2019 - 2024. All rights reserved.