Fellow Stranger
Fellow Stranger

Reputation: 34113

Passing default/static values from server to client

I have an input type with two fields used for filtering a query on the client.

I want to pass the default values (rentIntervalLow + rentIntervalHigh) from server to the client, but don't know how to do it.

Below is my current code. I've come up with two naïve solutions:

  1. Letting the client introspect the whole schema.

  2. Have a global config object, and create a querable Config type with a resolver that returns the config object values.

Any better suggestions than the above how to make default/config values on the server accessible to the client?

// schema.js
const typeDefs = gql`
  input FilteringOptions {
    rentIntervalLow: Int = 4000
    rentIntervalHigh: Int = 10000
  }

  type Home {
    id: Int
    roomCount: Int
    rent: Int
  }

  type Query {
    allHomes(first: Int, cursor: Int, input: FilteringOptions): [Home]
  }
`

export default typeDefs

I'm using Apollo Server 2.8.1 and Apollo React 3.0.

Upvotes: 0

Views: 1699

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84867

It's unnecessary to introspect the whole schema to get information about a particular type. You can just write a query like:

query {
  __type(name:"FilteringOptions") {
    inputFields {
      name
      description
      defaultValue
    }
  }
}

Default values are values that will be used when a particular input value is omitted from the query. So to utilize the defaults, the client would pass an empty object to the input argument of the allHomes field. You could also give input a default value of {}, which would allow the client not to provide the input argument at all, while still relaying the min and max default values to the resolver.

If, however, your intent is to provide the minimum and maximum values to your client in order to drive some client-specific logic (like validation, drop down menu values, etc.), then you should not utilize default values for this. Instead, this information should be queried directly by the client, using, for example, a Config type like you suggested.

Upvotes: 2

Related Questions