Graphql Cant返回数组

时间:2018-09-20 03:40:55

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

我正在使用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还是很陌生,因此感谢您的反馈!

1 个答案:

答案 0 :(得分:0)

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

tags: String!

这告诉GraphQL期望一个不为null的String值。 REST终结点返回的实际数据不是字符串,而是字符串数组。因此,您的定义至少应如下所示:

tags: [String]

如果您希望GraphQL在标签值为null时抛出,请在结尾处添加一个感叹号以使其不可为空:

tags: [String]!

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

tags: [String!]!