Skip to content

Instantly share code, notes, and snippets.

@modster
Created November 16, 2021 07:55
Show Gist options
  • Save modster/91fb22a077ea27543f49fa7a1a987e41 to your computer and use it in GitHub Desktop.
Save modster/91fb22a077ea27543f49fa7a1a987e41 to your computer and use it in GitHub Desktop.
Express and GraphQL API Passing Arguments
var dice = 3;
var sides = 6;
var query = `query RollDice($dice: Int!, $sides: Int) {
rollDice(numDice: $dice, numSides: $sides)
}`;
fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
variables: { dice, sides },
})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));

Passing Arguments

Just like a REST API, it's common to pass arguments to an endpoint in a GraphQL API. By defining the arguments in the schema language, typechecking happens automatically. Each argument must be named and have a type. For example, in the Basic Types documentation we had an endpoint called rollThreeDice:

https://graphql.org/graphql-js/passing-arguments/

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 {
rollDice(numDice: Int!, numSides: Int): [Int]
}
`);
// The root provides a resolver function for each API endpoint
var root = {
rollDice: ({numDice, numSides}) => {
var output = [];
for (var i = 0; i < numDice; i++) {
output.push(1 + Math.floor(Math.random() * (numSides || 6)));
}
return output;
}
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment