Search code examples
reactjsgraphqlapolloprisma

How can I specify optional query filters in Prisma?


I am building an application with React, Apollo and Prsima that allows users to filter cars by model, brand, price... I know (for example) how to filter cars by brand:

const GET_CARS = gql`
  query FilterCars($brandId: ID){
    cars(where: {   
        model : { brand: { id: $brandId } }
    }) {
        id
        model {
            name
            brand {
             name
            }
            horses
        }
        year
        km
        price
        ...
  }
`;

And in the component:

const CarList = (props) => {
    const { data, loading, error } = useQuery(GET_CARS, {
        variables: {
            brandId: "exampleBrandId"
        }
    })

    ...
}

The problem is, that some parameters are optional: maybe the user does not care about the brand, or the model, or the price... So then all cars should appear: If no brand is selected, cars of all brands should appear; If no price is selected, cars of all prices should appear...

How can I do that? Something like:

query FilterCars($brandId: ID){
    cars(where: {   
        model : { brand: { id: $brandId || all_brand_ids } }
    }) {
    ...
    }
}

I have investigated a and found a possible solution, but the custom input that the post refers to is not generated in my prisma.


Solution

  • getCars(parent, args, {prisma}, info){
      const queryArgs ={}
      if(args.brandId){
         queryArgs ={
           where: {
             model: {
              id: args.brandId
           }
          }
        }
      }
    
     if(args.price){
        queryArgs={
          ...queryArgs,
          where: {
          ...queryArgs.where
          //What every you want to add
          }
        }
     }
    
      return prisma.query.cars(queryArgs, info)
    }
    

    You can check on the Backend your args. And create a flexible obj to query for...