Katharina Schreiber
Katharina Schreiber

Reputation: 1371

Graphql Apollo Server Resolver: set of arguments for field and nested object

I am looking at this example in graphql docs:

{
  human(id: "1000") {
    name
    height(unit: FOOT)
  }
}

So, I'd like to built my schema and resolvers the way, that way that I can query similar. I have a list of Tacos :

const tacos = [
    {
      cathegory: 'meat',
      type: 'Al Pastor',
      like: false
    },
    {
      cathegory: 'meat',
      type: 'Barbacoa',
      like: false
    },
    {
      cathegory: 'meat',
      type: 'Chorizo',
      like: true
    },

  
    {
      cathegory: 'fish',
      type: 'Camaron',
      like: true
    },
    {
      cathegory: 'fish',
      type: 'Salmon',
      like: false
    },
    {
      cathegory: 'fish',
      type: 'Pulpo',
      like: false
    },

    {
      cathegory: 'veggi',
      type: 'Cauliflower',
      like: true
    },
    {
      cathegory: 'veggi',
      type: 'Avocado',
      like: true
    },
    {
      cathegory: 'veggi',
      type: 'Tofu',
      like: false
    },
]

My schema is super simple:

const typeDefs = gql`
  type Taco {
    cathegory: String
    type: String
    like: Boolean
  }

type Query {
  tacos(cathegory: String, like: Boolean): [Taco]
}
`;

I managed to write my resolver so that I cant filter according to the cathegory:

const resolvers = {
  Query: {
    tacos: (parent, args, context, info) => {
      return tacos.filter((taco) => taco.cathegory === args.cathegory);
    },
  },
};

So I can query as follows

query xyz {
  tacos(cathegory:"veggi" ) {
  like
}
}

But how can I write my resolver, so that I can query only veggi tacos where like is true? I am super new to this topic.

Upvotes: 0

Views: 309

Answers (1)

Fraction
Fraction

Reputation: 12954

Something like this:

const resolvers = {
  Query: {
    tacos: (parent, args, context, info) => {
      return tacos.filter((taco) => {
        if(Reflect.has(args, 'like')) {
          return taco.cathegory === args.cathegory && taco.like === args.like;
        }
        return taco.cathegory === args.cathegory;
      });
    },
  },
};

Upvotes: 1

Related Questions