platform/angel_graphql/lib/src/graphiql.dart

66 lines
2 KiB
Dart
Raw Normal View History

2018-08-02 17:02:00 +00:00
import 'package:angel_framework/angel_framework.dart';
2018-11-01 21:27:36 +00:00
import 'package:http_parser/http_parser.dart';
2018-08-02 17:02:00 +00:00
/// Returns a simple [RequestHandler] that renders the GraphiQL visual interface for GraphQL.
///
/// By default, the interface expects your backend to be mounted at `/graphql`; this is configurable
/// via [graphQLEndpoint].
RequestHandler graphiQL({String graphQLEndpoint: '/graphql'}) {
2018-08-02 17:02:00 +00:00
return (req, res) {
res
2018-11-01 21:27:36 +00:00
..contentType = new MediaType('text', 'html')
..write(renderGraphiql(graphqlEndpoint: graphQLEndpoint))
2018-11-01 21:27:36 +00:00
..close();
2018-08-02 17:02:00 +00:00
};
}
String renderGraphiql({String graphqlEndpoint: '/graphql'}) {
return '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angel GraphQL</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.min.css">
<style>
html, body {
margin: 0;
padding: 0;
}
html, body, #app {
height: 100%;
}
</style>
</head>
<body>
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script>
2018-08-04 19:18:53 +00:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.js"></script>
2018-08-02 17:02:00 +00:00
<script>
window.onload = function() {
function graphQLFetcher(graphQLParams) {
return fetch('$graphqlEndpoint', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(graphQLParams)
}).then(function(response) {
return response.json();
});
}
ReactDOM.render(
React.createElement(
GraphiQL,
{fetcher: graphQLFetcher}
),
document.getElementById('app')
);
};
</script>
</body>
</html>
'''
.trim();
}