Skip to content

Instantly share code, notes, and snippets.

@eezing
Last active July 15, 2018 16:51
Show Gist options
  • Save eezing/da80573eed81e5fae5658d90aaccbaea to your computer and use it in GitHub Desktop.
Save eezing/da80573eed81e5fae5658d90aaccbaea to your computer and use it in GitHub Desktop.

GraphQL Starter

Get Started

Run from a new project folder:

curl https://gist.githubusercontent.com/eezing/da80573eed81e5fae5658d90aaccbaea/raw/graphql-starter.sh | sh
#!/bin/sh
# Start with node-starter
curl https://gist.githubusercontent.com/eezing/6aa3b59137260916ea7fdd4040faa72a/raw/node-starter.sh | sh
# Clean up after node-starter
rm src/index.js
rm -rf coverage
# Create directories
mkdir src/graphql
mkdir src/static
# Download files
curl https://gist.githubusercontent.com/eezing/da80573eed81e5fae5658d90aaccbaea/raw/root_src_index.js --output src/index.js
curl https://gist.githubusercontent.com/eezing/da80573eed81e5fae5658d90aaccbaea/raw/root_src_static_index.html --output src/static/index.html
curl https://gist.githubusercontent.com/eezing/da80573eed81e5fae5658d90aaccbaea/raw/root_src_graphql_index.js --output src/graphql/index.js
curl https://gist.githubusercontent.com/eezing/da80573eed81e5fae5658d90aaccbaea/raw/root_src_graphql_schema.js --output src/graphql/schema.js
curl https://gist.githubusercontent.com/eezing/da80573eed81e5fae5658d90aaccbaea/raw/root_src_graphql_root.js --output src/graphql/root.js
# Install packages
npm install --save \
express \
body-parser \
graphql \
# Clean up
npm run pretty
# Run tests to create snapshots
npm test
# Commit
git add -A
git commit -m "Graphql scaffolding"
const { buildSchema, graphql } = require('graphql');
const sdl = require('./schema');
const rootValue = require('./root');
const schema = buildSchema(sdl, { commentDescriptions: true });
async function execute(query, variableValues, operationName, contextValue) {
return graphql(
schema,
query,
rootValue,
contextValue,
variableValues,
operationName
);
}
module.exports = execute;
module.exports = {
hello: () => 'world'
};
const gql = s => `${s}`;
module.exports = gql`
type Query {
hello: String!
}
`;
'use strict';
const PORT = process.env.PORT;
const express = require('express');
const bodyParser = require('body-parser');
const graphql = require('./graphql');
const app = express();
app.use(express.static(__dirname + '/static'));
app.use(bodyParser.json());
app.post('/graphql', async (req, res) => {
try {
const context = {};
const result = await graphql(
req.body.query,
req.body.variables,
req.body.operationName,
context
);
//eslint-disable-next-line
console.dir(
{
method: req.method,
context
},
{ depth: null, colors: true }
);
res.send(result);
} catch (error) {
res.status(500).send();
console.error(error); //eslint-disable-line
}
});
const listener = app.listen(PORT, err => {
if (err) throw err;
//eslint-disable-next-line
console.log('listening, port: %d', listener.address().port);
});
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 100%;
margin: 0;
width: 100%;
overflow: hidden;
}
#graphiql {
height: 100vh;
}
</style>
<script src="//cdn.jsdelivr.net/es6-promise/4.0.5/es6-promise.auto.min.js"></script>
<script src="//cdn.jsdelivr.net/fetch/0.9.0/fetch.min.js"></script>
<script src="//cdn.jsdelivr.net/react/15.4.2/react.min.js"></script>
<script src="//cdn.jsdelivr.net/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.css" />
</head>
<body>
<div id="graphiql"></div>
<script>
var search = window.location.search;
var parameters = {};
search.substr(1).split('&').forEach(function (entry) {
var eq = entry.indexOf('=');
if (eq >= 0) {
parameters[decodeURIComponent(entry.slice(0, eq))] =
decodeURIComponent(entry.slice(eq + 1));
}
});
// if variables was provided, try to format it.
if (parameters.variables) {
try {
parameters.variables =
JSON.stringify(JSON.parse(parameters.variables), null, 2);
} catch (e) {
// Do nothing, we want to display the invalid JSON as a string, rather
// than present an error.
}
}
// When the query and variables string is edited, update the URL bar so
// that it can be easily shared
function onEditQuery(newQuery) {
parameters.query = newQuery;
updateURL();
}
function onEditVariables(newVariables) {
parameters.variables = newVariables;
updateURL();
}
function onEditOperationName(newOperationName) {
parameters.operationName = newOperationName;
updateURL();
}
function updateURL() {
var newSearch = '?' + Object.keys(parameters).filter(function (key) {
return Boolean(parameters[key]);
}).map(function (key) {
return encodeURIComponent(key) + '=' +
encodeURIComponent(parameters[key]);
}).join('&');
history.replaceState(null, null, newSearch);
}
// Defines a GraphQL fetcher using the fetch API. You're not required to
// use fetch, and could instead implement graphQLFetcher however you like,
// as long as it returns a Promise or Observable.
function graphQLFetcher(graphQLParams) {
// This example expects a GraphQL server at the path /graphql.
// Change this to point wherever you host your GraphQL server.
return fetch('/graphql', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(graphQLParams),
credentials: 'include',
}).then(function (response) {
return response.text();
}).then(function (responseBody) {
try {
return JSON.parse(responseBody);
} catch (error) {
return responseBody;
}
});
}
// Render <GraphiQL /> into the body.
// See the README in the top level of this module to learn more about
// how you can customize GraphiQL by providing different values or
// additional child elements.
ReactDOM.render(
React.createElement(GraphiQL, {
fetcher: graphQLFetcher,
query: parameters.query,
variables: parameters.variables,
operationName: parameters.operationName,
onEditQuery: onEditQuery,
onEditVariables: onEditVariables,
onEditOperationName: onEditOperationName
}),
document.getElementById('graphiql')
);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment