In my query, could I use the result of a parameter to get more info in that query?

為{幸葍}努か 提交于 2019-12-03 20:58:21

问题


Forgive my terribly-worded question but here's some code to explain what I'm trying to do (slug and value are provided outside this query):

const query = `{
  post(slug: "${slug}") {
    content
    createdAt
    id <--- I want this id for my reply query
    slug
  }

  reply(replyTo: "id") { <--- The second query in question
    content
    createdAt
    id
    slug
  }

  user(id: "${value}") {
    username
  }
}`;

I just got started with GraphQL and I'm loving the fact that I can query multiple databases in one go. It'd be great if I could also perform some "queryception" but I'm not sure if this is possible.


回答1:


When thinking in terms of GraphQL, it's important to remember that each field for a given type is resolved by GraphQL simultaneously.

For example, when your post query returns a Post type, GraphQL will resolve the content and createdAt fields at the same time. Once those fields are resolved, it moved on to the next "level" of the query (for example, if content returned a type instead of a scalar, it would then try to resolve those fields.

Each of your individual queries (post, reply, and user) are actually fields of the Root Query type, and the same logic applies to them as well. That means there's no way to reference the id returned by post within reply -- both queries will be fired off at the same time.

An exception to the above exists in the form of mutations, which are actually resolved sequentially instead of simultaneously. That means, even though you still wouldn't be able to use the result of post as a variable inside your reply query, you could use context to pass the id from one to the other if both were mutations. This, however, is very hackish and requires the client to request the mutations in a specific order.

A more viable solution would be to simply handle this on the client side by breaking it up into two requests, and waiting to fire the second until the first one returns.

Lastly, you may consider reworking your schema to prevent having to have multiple queries in the first place. For example, your Post type could simply have a replies field that would resolve to all replies that correspond with the returned post's id.



来源:https://stackoverflow.com/questions/48482817/in-my-query-could-i-use-the-result-of-a-parameter-to-get-more-info-in-that-quer

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