How can I specify optional query filters in Prisma?

Viewed 3350

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.

3 Answers
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...

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

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

brandId: "exampleBrandId" - this should be dynamic, and one of the options could be something like "All Brands", which would then query all brands.

The answer from @Toiz is feasible. However, what if the number of parameters increases so that multiple if-statements are needed?

I suggest using undefined.

As mentioned in prisma official docs here, you can use undefined to optioanally exclude a field from query.

For example,

where: {   
  model : { 
    brand: { 
      id: $brandId != null ? $brandId : undefined
    } 
  }
}
Related