【问题标题】:Graphql Cant Return ArrayGraphql不能返回数组
【发布时间】:2018-09-20 21:01:21
【问题描述】:

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

{
  "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,并使用标签属性对其进行设置,但该值仅返回null

我对 graphql 很陌生,因此感谢任何反馈!

【问题讨论】:

  • 欢迎来到 SO!查看您的数据源代码也会很有帮助。您能否更新您的问题以将其也包含在内?
  • 好的,我已将其添加到问题中

标签: javascript graphql apollo graphql-js apollo-server


【解决方案1】:

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

tags: String!

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

tags: [String]

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

tags: [String]!

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

tags: [String!]!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-14
    • 2018-01-28
    • 2017-07-13
    • 2020-11-28
    • 2015-11-27
    • 2020-07-22
    • 2017-10-23
    • 2020-07-14
    相关资源
    最近更新 更多