Graphql 无法返回数组

foo*_*ing 3 javascript apollo graphql graphql-js apollo-server

我正在使用并尝试针对IEX REST APIApollo-Server创建 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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我正在使用数据源。我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)
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

数据源文件如下所示:

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

我可以运行查询并取回数据,但它没有在数组中格式化,并且当我运行查询时抛出错误,如下所示:

query{
  stock(symbol:"aapl"){
    tags
  }
}
Run Code Online (Sandbox Code Playgroud)

错误:

{
  "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\"]",
Run Code Online (Sandbox Code Playgroud)

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

我对 graphql 非常陌生,所以任何反馈都将受到赞赏!

Dan*_*den 5

在 的类型定义中Stock,您将该字段的类型定义tagsString!

tags: String!
Run Code Online (Sandbox Code Playgroud)

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

tags: [String]
Run Code Online (Sandbox Code Playgroud)

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

tags: [String]!
Run Code Online (Sandbox Code Playgroud)

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

tags: [String!]!
Run Code Online (Sandbox Code Playgroud)