Skip to content

Instantly share code, notes, and snippets.

@mikamboo
Last active August 2, 2019 12:53
Show Gist options
  • Select an option

  • Save mikamboo/bf59646aba0df28be9e895a8e6308404 to your computer and use it in GitHub Desktop.

Select an option

Save mikamboo/bf59646aba0df28be9e895a8e6308404 to your computer and use it in GitHub Desktop.
Play with GraphQL

Play with GraphQL !

Nous allons apprendre à créer en à peine quelques minutes, à créer un petite application GraphQL dans un environnement nodejs.

Prérequis

Step 1 : Création de notre projet

Il sera très simple et tiendra dans un seul fichier. Commençons donc par créer un dossier pour notre API et le fichier server.js

mkdir graphql-api
cd graphql-api
touch server.js

Step 2 : Installation des dépendances

Notre appli utisera les packages

  • express : Framework web pour nodejs
  • express-graphql : Middleware qui permet de créer le serveur GraphQL
  • graphql : Librairie JS qui implémente la spécification GraphQL
npm install --save express express-graphql graphql

Step 3 : Création de l'api (server.js)

Pour avoir un API GraphQL avec nodejs il faut :

  • Importer les dépendances
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
  • Créer un schéma qui définit les opération possibles avec les types de retour. GraphQL possède sont propolanguage de description de schéma qui est assez simple à comprendre.
var schema = buildSchema(`
  type Query {
    hello(name: String): String
    quote: String
    random: Float!
    roll(numDice: Int!, numSides: Int): [Int]
  }
`);
  • Créer l'implémentation des opérations ci-dessus déclarée
var root = {
  hello: (args) => {
    return `Hello ${args.name || 'world'} !`;
  },
  quote: () => {
    return Math.random() < 0.5 ? 'Take it easy' : 'Salvation lies within';
  },
  random: () => {
    return Math.random();
  },
  roll: (args) => {
    var output = [];
    for (var i = 0; i < args.numDice; i++) {
      output.push(1 + Math.floor(Math.random() * (args.numSides || 6)));
    }
    return output;
  }
};
  • Créer le serveur express HTTP GraphQL
var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
  • Lancer le serveur : Ici on le met à l'écoute sur le port 4000
app.listen(4000, '0.0.0.0');
console.log('Running a GraphQL API server at 0.0.0.0:4000/graphql');

Step 4 : Exécuter le programme qui va mettre en ligne notre API

node server.js

Retouvez le script complet du server.js ici.

Step 5 : Tester notre API

Dans la configuratino du server GraphQL nous avons activé graphiql qui est un puissant utilisatire qui permet de faire des requêtes graphql depuis un navigateur.

Pour accéder à l'interface de l'outil faut pour se rendre à l'adresse : http://localhost:4000/graphql.

image

Liens utiles

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
//-- Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello(name: String): String
quote: String
random: Float!
roll(numDice: Int!, numSides: Int): [Int]
}
`);
//-- The root provides a resolver function for each API endpoint
var root = {
hello: (args) => {
return `Hello ${args.name || 'world'} !`;
},
quote: () => {
return Math.random() < 0.5 ? 'Take it easy' : 'Salvation lies within';
},
random: () => {
return Math.random();
},
roll: (args) => {
var output = [];
for (var i = 0; i < args.numDice; i++) {
output.push(1 + Math.floor(Math.random() * (args.numSides || 6)));
}
return output;
}
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000, '0.0.0.0');
console.log('Running a GraphQL API server at 0.0.0.0:4000/graphql');
@mikamboo
Copy link
Copy Markdown
Author

mikamboo commented Aug 2, 2019

GraphQL

image

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