What do you think about this filtering system?

Dear people,

I'm trying to add in my app a new filtering system.

Here the code in the Rust Playground.

I'm trying to use enums like this:

pub struct ProductFilter {
    pub id: Option<IdFilter>,
    pub created_at: Option<DateTimeFilter>,
    pub created_by: Option<IdFilter>,
    pub updated_at: Option<Nullable<DateTimeFilter>>,
    pub updated_by: Option<Nullable<IdFilter>>,
    pub name: Option<StringFilter>,
    pub price: Option<IntFilter>,
    pub and: Option<Vec<ProductFilter>>,
    pub or: Option<Vec<ProductFilter>>,
    pub not: Option<Box<ProductFilter>>,
}
  1. I don't know if creating IdFilter, DateTimeFilter, StringFilter etc. enums is a great idea; but I think is a pratical way to have precise, compile-time types correctness;

    pub enum StringFilter {
        Eq(String),
        Neq(String),
        In(Vec<String>),
        Contains(String),
        StartsWith(String),
        EndsWith(String),
    }
    
  2. Some field can be Nullable and I need a way to express that in the DB query, so I wrote:

    pub enum Nullable<T> {
        Filter(T),
        IsNull(bool),
        IsNotNull(bool),
    }
    

    I'm not very proud of it, but nothing else came to mind. What do you recommend? I thought about having nested Option<> but I need to be able to express IS NULL and IS NOT NULL and I could end up with Option<Option<Option<>>>: not very practical.

Looking forward to hearing your advice!

How about passing a vector of "filters"? This could be a trait that you then implement for subfilters (StringFilter, IDFilter, etc). The trait/filters could have options for null or not null, and because you're only applying the filters that are passed in the list, you don't need to wrap them in nested options. Just some food for thought. :slight_smile:

EDIT: I feel like I should mention that I'm just your average hobbyist. Someone with more experience working with production environments may have better advice. Take my advice with a pinch of salt!

1 Like

Interesting, can you write an example?

Not too familiar with graphQL unfortunately, sorry!

Nope, I'm asking for a rust example.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.