将参数传递给 graphQL 查询

Mat*_*nis 5 graphql graphql-js

我正在努力在 node.js 中设置一个 graphQL 模式。该/graphql终端通常会与传递的参数(S)击中。例如,一个 API 调用可能正在寻找“检查”帐户:

query {
  accounts(type: "checking") {
    id
    type
    country
    currency
  }
}
Run Code Online (Sandbox Code Playgroud)

另一个可能正在寻找“美国”的所有帐户:

query {
  accounts(country: "US") {
    id
    type
    country
    currency
  }
}
Run Code Online (Sandbox Code Playgroud)

...还有一个可能正在寻找以“英镑”计价的“英国”中的“储蓄”账户:

query {
  accounts(type: "savings", country: "UK", currency: "GBP") {
    id
    type
    country
    currency
  }
}
Run Code Online (Sandbox Code Playgroud)

是否选择了正确的方法定义此查询作为可选项的参数typecountrycurrency

nbu*_*urk 3

这实际上取决于您想要如何设计 API,这个答案没有对错之分,我不确定通常是否有正确的方法。

但是,如果您确定所描述的场景,那么是的,typecountrycurrency应该是可选的,因为您在某些查询中将它们排除在外。如果您没有将这些设置为可选,那么如果未传入它们,您的 GraphQL 服务器将会抛出错误。

另一种选择可能是将所有这些参数包装在filter带有可选字段的对象中。另外,typecurrencycountry可能更好地表示为枚举而不是字符串:)