Reputation: 15298
Take the following Github URL: https://github.com/google
How can I determine whether google
is a user or an organization?
I need to know to this for querying Github's graphql API in the correct way.
Upvotes: 1
Views: 83
Reputation: 941
Query repositoryOwner
. Use its __typename
.
Query:
query ($login: String!) {
repositoryOwner(login: $login) {
__typename
}
}
Variables:
{"login": "google"}
{"login": "torvalds"}
Which yields
{
"data": {
"repositoryOwner": {
"__typename": "Organization"
}
}
}
{
"data": {
"repositoryOwner": {
"__typename": "User"
}
}
}
If you are looking for some common properties, and don't care whether the subject is a user or an organization. You can try something like:
query ($login: String!) {
repositoryOwner(login: $login) {
avatarUrl
}
}
You may want to use another common ancestor interface for properties that repositoryOwner
lacks:
query ($login: String!) {
repositoryOwner(login: $login) {
... on ProfileOwner {
name
}
}
}
Even dispatch to different fields depending on the concrete object type: (credited to Bertrand Martel's another answer)
query ($login: String!) {
repositoryOwner(login: $login) {
... on User {
bio
}
... on Organization {
description
}
}
}
The all-in-one combination,
query ($login: String!) {
repositoryOwner(login: $login) {
avatarUrl
... on ProfileOwner {
name
}
... on User {
bio
}
... on Organization {
description
}
}
}
providing the following variables,
{"login": "microsoft"}
{"login": "munificent"}
yields:
{
"data": {
"repositoryOwner": {
"avatarUrl": "https://avatars.githubusercontent.com/u/6154722?v=4",
"name": "Microsoft",
"description": "Open source projects and samples from Microsoft"
}
}
}
{
"data": {
"repositoryOwner": {
"avatarUrl": "https://avatars.githubusercontent.com/u/46275?v=4",
"name": "Bob Nystrom",
"bio": "Programming language developer, ex-game developer, UI nerd, author of \"Game Programming Patterns\" and \"Crafting Interpreters\"."
}
}
}
Upvotes: 0
Reputation: 45513
If you have the login (username) of the user/group, you can use organization
& user
to search respectively an organization & a user and check which of the 2 fields is not null
:
{
org: organization(login: "google") {
name
members {
totalCount
}
}
user: user(login: "google") {
name
login
}
}
which gives :
{
"data": {
"org": {
"name": "Google",
"members": {
"totalCount": 1677
}
},
"user": null
}
}
or using a variable for login
input, try it in the explorer
For the Rest API v3, it's much simpler since it doesn't distinguish the user from the organization : https://developer.github.com/v3/users :
curl -s 'https://api.github.com/users/google' | jq -r '.type'
Organization
curl -s 'https://api.github.com/users/torvalds' | jq -r '.type'
User
Upvotes: 1