Graphql Cant Return 数组

Graphql Cant Return Array

我正在使用 Apollo-Server 并尝试针对 IEX REST API 创建一个 REST 查询,其中 returns 返回数据如下所示:

{
  "symbol": "AAPL",
  "companyName": "Apple Inc.",
  "exchange": "Nasdaq Global Select",
  "industry": "Computer Hardware",
  "website": "http://www.apple.com",
  "description": "Apple Inc is an American multinational technology company. It designs, manufactures, and markets mobile communication and media devices, personal computers, and portable digital music players.",
  "CEO": "Timothy D. Cook",
  "issueType": "cs",
  "sector": "Technology",
  "tags": [
      "Technology",
      "Consumer Electronics",
      "Computer Hardware"
  ]
}

我正在使用 datasources。我的 typeDefsresolvers 看起来像这样:

const typeDefs = gql`
    type Query{
        stock(symbol:String): Stock
    }

    type Stock {
        companyName: String
        exchange: String
        industry: String
        tags: String!
    }
`;
const resolvers = {
    Query:{
        stock: async(root, {symbol}, {dataSources}) =>{
            return dataSources.myApi.getSomeData(symbol)
        }
    }
};

数据源文件如下所示:

class MyApiextends RESTDataSource{
    constructor(){
        super();
        this.baseURL = 'https://api.iextrading.com/1.0';
    }

    async getSomeData(symbol){
        return this.get(`/stock/${symbol}/company`)
    }
}

module.exports = MyApi

我可以 运行 查询并取回数据,但它没有在数组中格式化,并且当我 运行 像这样的查询时抛出错误:

query{
  stock(symbol:"aapl"){
    tags
  }
}

错误:

{
  "data": {
    "stock": null
  },
  "errors": [
    {
      "message": "String cannot represent value: [\"Technology\", \"Consumer Electronics\", \"Computer Hardware\"]",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ],
      "path": [
        "stock",
        "tags"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "TypeError: String cannot represent value: [\"Technology\", \"Consumer Electronics\", \"Computer Hardware\"]",

我期望的数据(技术、消费电子产品和计算机硬件)是正确的,但没有以数组形式返回。我试图为标签创建一个新的 type,并用标签 属性 设置它,但值只是 returns null.

我是 graphql 的新手,非常感谢任何反馈!

Stock 的类型定义中,您将 tags 字段的类型定义为 String!:

tags: String!

这告诉 GraphQL 期望一个不会为 null 的字符串值。然而,REST 端点返回的实际数据不是字符串——它是字符串数组。所以你的定义至少应该是这样的:

tags: [String]

如果您希望 GraphQL 在标签值为 null 时抛出异常,请在末尾添加感叹号以使其不可为 null:

tags: [String]!

如果您希望 GraphQL 在数组 中的任何值 为 null 时抛出异常,请在括号内添加感叹号。您也可以将两者结合起来:

tags: [String!]!