typescriptnext.jsgraphql

I need a query like this in graphql but I can't figure out how to do it


I am making a car rental application to improve myself. .../vehicles address lists vehicles, I have 5 select inputs on the left side bar. If a value is selected, I want it to have a filter, if it is not selected, I want it to have no filter. I could not structure how to send the query and data. Can you help me?

subscription Vehicles($daily_price: String) {
      vehicles(where: { _or: { daily_price: $daily_price, fuel: {}, gear: {}, model_id: {}, brand_id: {} } }) {
  id
  fuel
}
const { data, loading, error } = useSubscription(from && to ? VEHICLES_BY_DATE_RANGE : VEH_SUBS, {
      variables: {
         ...filters,
      },
   });

Solution

  • Alright, here's a sketch on how to work with variables. The type declaration are just based on what I assume to be correct based on your code snippets, so you might have to adjust them.

    // I'm skipping the definition of how the Where filters, so here's just the query:
    const VEH_SUBS = gql`
      subscription getVehicles($where: Where!) {
        vehicles(where: $where) {
          model {
            name
          }
        }
      }`;
    
    // I'm assuming the type of the filters based on your code snippets. They could be wrong (e.g. brand_id could be a number).
    const createQuery = (filters: { brand_id?: string, fuel?: string, }) => {
      // I'm assuming the type of the filterConditions based on your code snippets. It's probably not complete. 
      const filterConditions: {
        where: { _or: { brand_id?: { _eq?: string }, fuel?: { _eq?: string } } }
      } = { where: { _or: {} } };
    
      // Setup filterConditions. Ofc, this could be done direclty in the line above, but I keep it separate so it might be easier to follow.
      if (filters?.brand_id) filterConditions.where._or.brand_id = { _eq: filters.brand_id };
      if (filters?.fuel) filterConditions.where._or.fuel = { _eq: filters.fuel };
    
      const { data: d, loading: l, error: e } = useSubscription(
        VEH_SUBS, // This should be a query which accepts where as argument!
        { variables: {where: filterConditions }}
      );
      ...
    };
    

    Again, I'ld recommend you to utilize graphql-codegen instead of explicit type assumption as I did, and also instead of any as you did.