Modeling optional filter params in react-apollo

元气小坏坏 提交于 2019-12-08 12:23:16

问题


I am using react-apollo to access a graphql in a web app.

I have a query that looks like this that allows me to filter a schedule of games:

query($pagination:Int!, $divisionId:ID, $teamId:ID, $startDate:DateTime!, $endDate:DateTime!
){
 games: allGames (
 orderBy: date_ASC,
 first: $pagination,
 filter: {
   date_gte: $startDate,
   date_lte: $endDate,
   division: {id: $divisionId},
   OR: [
    {homeTeam: {id: $teamId} },
    {awayTeam: {id: $teamId} },
   ]
  }
){
 id
 .... more fields
}

The startDate and endDate variables are required for every request, but the teamId and divisionId are not. I would like to display all teamIds and divisionIds in the initial request, and allow the use to filter / drill down as needed.

I was looking to see if I could add a wildcard (*) or something of that sort, but I am not sure if it's possible. With graphql mutations, a null value for a variable allows me to write a single mutation that is applicable to multiple use cases (partial updates & creates), but I cannot figure out how to achieve similar functionality with queries.

Do I need to call a different query for each of the filter scenarios (one for no divisionId & teamId, one for just divisionId, one for just teamId, and one for both divisionId and teamId? Are fragments something that would help me achieve this with less overhead (because the last sentence makes the process seem a bit too cumbersome / not DRY).

Or do i switch division and id to division_in and id_in and pass them (somewhat large) arrays with all the possible values for divisionIds and teamdIds as initial props?


回答1:


So it turns out you an actually store the entire filter as a variable (which is pretty awesome).

Here is the updated query:

query( $first:Int!, $skip:Int!, $gameFilter:GameFilter! ){
  games: allGames (
    orderBy: date_ASC,
    first: $first,
    skip: $skip,
    filter: $gameFilter
  ){
    id
    ... more fields
   }
}

And the corresponding HOC:

export default graphql(gamesQuery, {
  options: props => ({
    return { variables: {props.gameFilter}
  });
})(GamesPage);

Hat tip to these guys:

  • https://www.graph.cool/forum/t/optional-query-filters/355
  • https://www.graph.cool/forum/t/is-it-possible-to-build-a-filter-query-dynamically/268


来源:https://stackoverflow.com/questions/46382505/modeling-optional-filter-params-in-react-apollo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!