【问题标题】:get Index from an Array using Express + GraphQL使用 Express + GraphQL 从数组中获取索引
【发布时间】:2019-01-03 21:59:27
【问题描述】:

我只是在使用 Express 对 GraphQL 进行操作。我正在关注Academind YouTube Series for GraphQL-Express-Node-React。我刚刚设置了一个基本的 GraphQL Schema,我在其中硬编码了返回的字符串数组。我想创建一个查询,它使用 GraphQL (graphiql) 为我提供该硬编码数组中元素的索引

代码

const express = require('express'); // Add Express Module
const bodyParser = require('body-parser'); // Add Body-Parser Middleware for JSON handling in Requests
const graphqlHttp = require('express-graphql'); // Add Middleware for GraphQL Resolvers over Express HTTP
const { buildSchema } = require('graphql'); // Javascript Object-Destructuring (pull objects from packages)

const app = express();

app.use(bodyParser.json()); // JSON parsing Middleware added

app.use('/graphql', graphqlHttp({
    schema: buildSchema(`
        type RootQuery {
            events: [String!]!
            getEventIndex(eventName: String): Int
        }

        type RootMutation {
            createEvent(name: String): String
        }

        schema {
            query: RootQuery
            mutation: RootMutation
        }
    `),
    rootValue: {
        events: () => {
            return ['Cooking', 'All-Night Coding', 'Romantic'];
        },
        getEventIndex: (args) => {
            const _arr = ['Cooking', 'All-Night Coding', 'Romantic'];
            const index = _arr.findIndex(args.eventName);
            return index;
        },
        createEvent: (args) => {
            const eventName = args.name; // same as that of the parameter for `createEvent`
            return eventName;

        }
    },
    graphiql: true
}));

app.listen(3000);

我创建了一个查询getEventIndex(eventName: String): Int,它接受事件名称并为我提供索引(整数)

结果为@​​987654325@

查询

query {
  getEventIndex(eventName: "Cooking")
}

结果

{
  "errors": [
    {
      "message": "Cooking is not a function",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "getEventIndex"
      ]
    }
  ],
  "data": {
    "getEventIndex": null
  }
}

为什么Cooking 在这里被视为function 而不是createEvent 突变中的参数?

当然,我在没有深入了解其规范的情况下直接进入 GraphQL,但我想它也可能能够处理基于参数的查询。

【问题讨论】:

    标签: node.js express graphql


    【解决方案1】:

    此错误并非特定于 GraphQL。

    Array.findIndex 期望将函数作为其第一个参数传入。为数组中的每个元素调用该函数,直到该函数返回一个真实值,此时它返回该元素的索引。 args.eventName 的值不是一个函数(它是一个字符串),所以你最终会遇到这个错误。

    要么给它一个函数,比如:

    const index = _arr.findIndex(value => value === args.eventName)
    

    或者只是使用Array.indexOf,这可能是你的意思:

    const index = _arr.indexOf(args.eventName)
    

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 2017-03-19
      • 2020-06-19
      • 2018-06-06
      • 2022-10-19
      • 1970-01-01
      • 2018-08-18
      • 2016-02-03
      • 2020-05-04
      相关资源
      最近更新 更多