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));
return cars.filter(car => car.color === args.color);
}
console.log(cars);
return cars;
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
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");
});
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
}
}
}