GraphQL Tutorial — Getting Started

Introduction

Architecture

First steps

git clone git@github.com:thebigredgeek/esnext-node-starterkit.git graphql-demo
cd graphql-demo
npm install
touch src/resolvers.js
touch src/schema.js

Schema

/* src/schema.js */
const schema = `
schema {
query: Query
}
`;
/* src/schema.js */...const Query = `
type Query {
helloWorld: String!
}
`;
/* src/schema.js */...export default [
schema,
Query
];

Resolvers

/* src/resolvers.js */
export default {
Query: {
// Our only Resolver, which belongs to the `Query`
// Type that we defined before
helloWorld: () => 'Hello World!' // Returns a String
}
};

To Hello World…

npm install express body-parser graphql graphql-server-express graphql-tools
/* src/index.js */
import 'source-map-support/register';
import 'babel-polyfill';
import express from 'express';
import bodyParser from 'body-parser';
import { graphqlExpress } from 'graphql-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import resolvers from './resolvers';
import schema from './schema';
const app = express();const executableSchema = makeExecutableSchema({
typeDefs: schema,
resolvers
});
app.post('/graphql',
bodyParser.json(),
graphqlExpress(() => ({
schema: executableSchema
}))
);
app.listen(8080);
npm run watch
query demo {
helloWorld
}
curl -X POST http://localhost:8080/graphql -d '{"query": "query demo { helloWorld }" }' -H 'Content-Type: application/json'
{
"data": {
"helloWorld": "Hello World!"
}
}

And beyond…

/* src/schema.js */
const schema = `
schema {
query: Query
}
`;
const Query = `
type Query {
hello: Hello!
}
`;
const Hello = `
type Hello {
world: World!
}
`;
const World = `
type World {
text: String!
}
`;
export default [
schema,
Query,
Hello,
World
];
/* src/resolvers.js */
class Hello {
constructor () {
this.world = new World();
}
}
class World {
constructor () {
this.text = 'Hello world!';
}
}
export default {
Query: {
// Our only Resolver, which belongs to the `Query`
// Type that we defined before
hello: () => new Hello() // Return an instance of the Hello class
},
// Uppercase "Hello", the same as the name of the Type in `src/schema.js`
Hello: {
// Tell GraphQL how to get from an instance of Hello to `instance.world`
world: hello => hello.world
}
};
/* src/index.js */
...
// Import graphiqlExpress, a UI tool for testing GraphQL APIs
import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';
...// Add GraphiQL Middleware
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}));
app.listen(8080);
query {
hello {
world {
text
}
}
}

In conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store