Skip to content

Instantly share code, notes, and snippets.

@Eboubaker
Last active November 29, 2021 19:48
Show Gist options
  • Save Eboubaker/ed5d955918de35c6027173a76aa7fd03 to your computer and use it in GitHub Desktop.
Save Eboubaker/ed5d955918de35c6027173a76aa7fd03 to your computer and use it in GitHub Desktop.

Make filtering needs on the client side

Intro

I got this idea when i knew that if you do console.log on a function you will get the source code of it

const filter = user => !user.deleted && user.age > 19
console.log(filter.toString)// "user => !user.deleted && user.age > 19"

Frontend

We might be able to use this as a filter for graphql request with the combination of input filters, we parse the source code of filter function into a graphql input filters and send them with the request. as an example lets call our extractor function "extractFilters", The extractor should extract an array of filters such that the filter is definied as

interface Filter{
  property: string;
  operator: string;
  value: string;
}

As an example we can create an array of filters for the above filter function

const filter = user => !user.deleted && user.age > 19
const filters = extractFilters(filter)
console.log(filter)

The result is an array of Filters

[
  {
    "property": "deleted",
    "operator": "=",
    "value": false
  },
  {
    "property": "age",
    "operator": ">",
    "value": 19
  }
]

GraphQL

The graphql Filter should be as follows

input Filter {
  property: String!
  operator: String!
  value: String!
}

and the usage for the query should be as follows

# USERS_QUERY
query{
  findUsersByFilter(filter: Filter){
    id
    name
    age
  }
}

Frontend usage

The final usage in our code

const filter = user => !user.deleted && user.age > 19
apollo.query({
  query: USERS_QUERY,
  variables:{
    filter: extractFilters(filter)
  }
}).then(users => {
  // users are non deleted and their age is greater than 19
});

Spring boot

TODO

Notes

How to implement nested "and", "or" operations, Hint: use nested arrays (each group of arrays are "or"s, each filter inside an array is an "and")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment