问题描述
我将如何使用具有不同参数的Apollo查询.假设我的应用程序具有用户的概念,我希望我的API能够通过ID或用户名找到用户.
看来我不能做这个
type Query { user(id: ID!): User user(username: String!): User }
我必须求助于这样的东西
type Query { userById(id: ID!): User userByUsername(username: String!): User }
推荐答案
创建具有ID和用户名作为字段的新输入类型,并将其指定为参数.
type Query { getUser(filters:UserFilter): User } input UserFilter{ ID : Int, Username : String }
查询应该看起来像这样...
Query{ getUser(filters:{ID:123123}) }
或用于用户名滤镜
Query{ getUser(filters:{Username:"Tom"}) }
其他推荐答案
我相信您的第二个选择是最好的,但是您可以做这样的事情.
type Query { user(id: ID, username: String): User }
如果不需要参数,则您的解析器可以使用一些逻辑来确定是否应根据ID或用户名获得用户.
if (args.id) { return getUserById(args.id) } else { return getUserByUsername(args.username) }
然而,出于理由在这次演讲中 https://youtu.be/pjamhw2xpyw?t (也许在12:30见),我相信您的第二个选择是更好的设计选择.希望有帮助!
问题描述
How would I go about having an Apollo query with different parameters. Let's say my app has the concept of users and I want my API to be able to find a user either by ID or username.
It doesn't seem I can do this
type Query { user(id: ID!): User user(username: String!): User }
do I have to resort to something like this
type Query { userById(id: ID!): User userByUsername(username: String!): User }
推荐答案
Create a new input type with ID and username as fields and specify it as parameter.
type Query { getUser(filters:UserFilter): User } input UserFilter{ ID : Int, Username : String }
Query should look like this ...
Query{ getUser(filters:{ID:123123}) }
OR for username filter
Query{ getUser(filters:{Username:"Tom"}) }
其他推荐答案
I believe your second option is the best however you could do something like this.
type Query { user(id: ID, username: String): User }
If the parameters are not required then your resolver could use some logic to determine if it should get the user based on the id or the username.
if (args.id) { return getUserById(args.id) } else { return getUserByUsername(args.username) }
However for reasons gone over in this talk https://youtu.be/pJamhW2xPYw?t=750 (maybe see at about 12:30), I believe your second option is a better design choice. Hope that helps!