简体   繁体   中英

Apollo / GraphQL Same Query with Different Parameters

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
}

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!

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"})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM