Click here to Skip to main content
15,891,597 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
JavaScript
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 file
JavaScript
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");
});


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 query (Trying to get the list of all the cars)

{
  cars{
    name
  }
}


What I get
{
  "data": {
    "cars": {
      "name": null
    }
  }
}
Posted
Updated 6-Mar-19 2:40am
v2

1 solution

How about
type: new GraphQLList(CarType)

and then always resolve your result to array?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900