Skip to content

Instantly share code, notes, and snippets.

@devknoll
Last active June 13, 2022 00:07
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save devknoll/8b274f1c5d05230bfade to your computer and use it in GitHub Desktop.
Save devknoll/8b274f1c5d05230bfade to your computer and use it in GitHub Desktop.
Basic GraphQL example using the GitHub API
import { graphql, GraphQLString, GraphQLInt } from 'graphql';
import { objectType, enumType, schemaFrom, listOf } from 'graphql-schema';
import request from 'promisingagent';
const repositorySortEnum = enumType('RepositorySort')
.value('CREATED', 'created')
.value('UPDATED', 'updated')
.value('PUSHED', 'pushed')
.value('FULL_NAME', 'full_name')
.end();
const repositoryType = objectType('Repository')
.field('id', GraphQLString)
.field('name', GraphQLString)
.field('owner', () => userType)
.field('description', GraphQLString)
.end();
const userType = objectType('User')
.field('id', GraphQLString)
.field('name', GraphQLString)
.field('login', GraphQLString)
.field('location', GraphQLString)
.field('repositories', listOf(repositoryType))
.arg('first', GraphQLInt)
.arg('orderby', repositorySortEnum)
.resolve((user, {first, orderby}) => fetchRepositoriesFor(user.name, first, orderby))
.end();
const queryType = objectType('Query')
.field('user', userType)
.arg('name', GraphQLString)
.resolve((root, {name}) => fetchUser(name))
.end();
const query = `
{
user(name: "facebook") {
name,
repositories(first: 5, orderby: FULL_NAME) {
name,
description
}
}
}
`;
graphql(schemaFrom(queryType), query).then(result => {
console.log(JSON.stringify(result));
});
function fetchUser(name) {
return request
.get(`https://api.github.com/users/${name}`)
.end().then(result => {
return result.body;
});
}
function fetchRepositoriesFor(name, first, orderby) {
return request
.get(`https://api.github.com/users/${name}/repos?per_page=${first}&sort=${orderby}`)
.end().then(result => {
return result.body;
});
}
@undoZen
Copy link

undoZen commented Oct 10, 2015

you can just

return request(`https://api.github.com/users/${name}/repos?per_page=${first}&sort=${orderby}`)
  .get('body')

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment