/user.go Secret
Created
August 25, 2020 17:57
Retrieve a single user from the REST endpoint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// UserField is a field that returns a single user | |
var UserField = &graphql.Field{ | |
Type: userObject, | |
Args: graphql.FieldConfigArgument{ | |
"user_id": &graphql.ArgumentConfig{ | |
Description: "The ID of the user you want to retrieve", | |
Type: graphql.NewNonNull(graphql.Int), | |
}, | |
}, | |
Resolve: func(p graphql.ResolveParams) (interface{}, error) { | |
return fetchSingleUser(p.Args["user_id"].(int)), nil | |
}, | |
} | |
// Find a single user for the given userID | |
func fetchSingleUser(userID int) models.User { | |
response, err := http.Get("https://jsonplaceholder.typicode.com/users/" + strconv.Itoa(userID)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
responseData, err := ioutil.ReadAll(response.Body) | |
if err != nil { | |
log.Fatal(err) | |
} | |
var user models.User | |
err = json.Unmarshal(responseData, &user) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return user | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment