如何在graphql中返回一个对象数组

如何在graphql中返回一个对象数组

本文介绍了如何在graphql中返回一个对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个graphql api,我可以通过id获取汽车,按颜色过滤汽车或在没有提供参数时返回所有汽车。



在下面的代码中,从数组中获取单个对象,即当我提供id时。但是,当我返回数组内的对象时,它不会返回对象。



我试图在返回之前打印数组,但我仍然不知道为什么它不通过graphql。




$ b $架构文件夹中的schema.js文件

I am making a graphql api where I would be able to get car by id, filter cars by color or return all the cars when no paramater is provided.

In the code below, getting a single object out of the array works i.e when I provide the id. However it does not return the objects when I return those inside an array.

I have tried to print the array write before it gets returned but still I do not know why it does not go through graphql.


schema.js file inside schema folder

const graphql = require("graphql");
const { GraphQLObjectType, GraphQLString, GraphQLSchema } = graphql;

let cars = [
  { name: "Honda", color: "Red", id: "1" },
  { name: "Toyota", color: "Blue", id: "2" },
  { name: "BMW", color: "Blue", id: "3" }
];

const CarType = new GraphQLObjectType({
  name: "Car",
  fields: () => ({
    id: { type: GraphQLString },
    name: { type: GraphQLString },
    color: { type: GraphQLString }
  })
});

const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    cars: {
      type: CarType,
      args: {
        id: { type: GraphQLString },
        color: { type: GraphQLString }
      },
      resolve(parent, args) {
        if (args.id) {
          return cars.find(car => (car.id = args.id));
        }
        if (args.color) {
          console.log(cars.filter(car => car.color === args.color));
          //Problem here
          return cars.filter(car => car.color === args.color);
        }

        console.log(cars);
        //And Problem Here
        return cars;
      }
    }
  }
});

module.exports = new GraphQLSchema({
  query: RootQuery
});







app.js文件




app.js file

const express = require("express");
const graphqlHTTP = require("express-graphql");
const schema = require("./schema/schema");

const app = express();

app.use("/graphql", graphqlHTTP({ schema, graphiql: true }));

app.listen(4000, () => {
  console.log("Now listening for requests on port 4000");
});





我的尝试:



正如你所看到的,我试图在返回之前打印出阵列。



有趣的是阵列按预期打印但是在graphql前端,它没有给我任何结果。





GraphQL查询(按颜色过滤)





What I have tried:

As you can see, I have tried to print out the array right before returning it.

The funny thing is the array is printed as expected but on the graphql front end, it gives me no result.


GraphQL query (filtering by color)

{
  cars(color:"blue") {
    name
  }
}







GraphQL查询(试图获取所有车辆的清单)






GraphQL query (Trying to get the list of all the cars)

{
  cars{
    name
  }
}





我得到了什么



What I get

{
  "data": {
    "cars": {
      "name": null
    }
  }
}

推荐答案

type: new GraphQLList(CarType)



然后总是将结果解析为数组?


and then always resolve your result to array?


这篇关于如何在graphql中返回一个对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:47