Skip to content

Instantly share code, notes, and snippets.

@kevincennis
Last active July 9, 2020 17:31
Show Gist options
  • Save kevincennis/d966b3f88b3499b293a83abf63e0701b to your computer and use it in GitHub Desktop.
Save kevincennis/d966b3f88b3499b293a83abf63e0701b to your computer and use it in GitHub Desktop.
GraphQL Demo
{
"users": [
{
"id": 1,
"name": "John",
"email": "john@foo.com",
"address": 4
},
{
"id": 2,
"name": "Jane",
"email": "jane@foo.com",
"address": 5
},
{
"id": 3,
"name": "Bob",
"email": "bob@foo.com",
"address": 5
}
],
"addresses": [
{
"id": 4,
"house_number": "1",
"street": "First Street",
"city": 6
},
{
"id": 5,
"house_number": "2",
"street": "Second Street",
"city": 7
}
],
"cities": [
{
"id": 6,
"name": "Boston",
"state": "MA"
},
{
"id": 7,
"name": "New York",
"state": "NY"
}
]
}
const { graphql } = require('graphql');
const schema = require('./schema');
const log = x => console.log( JSON.stringify( x, null, 2 ) );
const query = `{
user(id:2) {
id,
name,
email,
address {
id,
house_number,
street,
users {
id,
name
},
city {
id,
name,
state
}
}
}
}`;
graphql( schema, query ).then( log );
{
"name": "graphql-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"dataloader": "^1.4.0",
"graphql": "^14.0.2",
"graphql-tools": "^3.1.1"
}
}
const { users, addresses, cities } = require('./data');
const DataLoader = require('dataloader');
const userLoader = new DataLoader(
async keys => users.filter( d => keys.includes( d.id ) )
);
const addressLoader = new DataLoader(
async keys => addresses.filter( d => keys.includes( d.id ) )
);
const cityLoader = new DataLoader(
async keys => cities.filter( d => keys.includes( d.id ) )
);
module.exports = {
Query: {
async user( root, { id } ) {
return userLoader.load( id );
},
async users() {
return [ ...users ];
}
},
User: {
async address({ address }) {
return addressLoader.load( address );
}
},
Address: {
async city({ city }) {
return cityLoader.load( city );
},
async users({ id }) {
return users.filter( d => d.address === id );
}
}
};
type Query {
user(id: Int!): User,
users: [ User ]
},
type User {
id: Int,
name: String,
email: String,
address: Address
},
type Address {
id: Int,
house_number: String,
street: String,
city: City,
users: [ User ]
}
type City {
id: Int,
name: String,
state: String
}
schema {
query: Query
}
const fs = require('fs');
const resolvers = require('./resolvers');
const { makeExecutableSchema } = require('graphql-tools');
const typeDefs = fs.readFileSync( 'schema.graphql', 'utf8' );
module.exports = makeExecutableSchema({ typeDefs, resolvers });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment