-
-
Save kevinold/de3b3f9cbf4daeb4be91f501d5721026 to your computer and use it in GitHub Desktop.
Basic GraphQL example using the GitHub API
This file contains hidden or 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
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; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment