Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

graphiql #106

Merged
merged 2 commits into from
Dec 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ libraryDependencies ++= Seq(
"com.github.ghostdogpr" %% "caliban-cats" % "0.3.0"
)
```

Run `ExampleApp` and open [http://localhost:8088/graphiql](http://localhost:8088/graphiql)
156 changes: 156 additions & 0 deletions examples/src/main/resources/graphiql.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<!-- https://raw.githubusercontent.com/graphql/graphiql/master/packages/examples/graphiql-cdn/index.html -->
<!--
* Copyright (c) 2019 GraphQL Contributors
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
-->
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 100%;
margin: 0;
width: 100%;
overflow: hidden;
}
#graphiql {
height: 100vh;
}
</style>

<!--
This GraphiQL example depends on Promise and fetch, which are available in
modern browsers, but can be "polyfilled" for older browsers.
GraphiQL itself depends on React DOM.
If you do not want to rely on a CDN, you can host these files locally or
include them directly in your favored resource bunder.
-->
<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>

<!--
These two files can be found in the npm module, however you may wish to
copy them directly into your environment, or perhaps include them in your
favored resource bundler.
-->
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/graphiql@0.16.0/graphiql.css" />
<script src="//cdn.jsdelivr.net/npm/graphiql@0.16.0/graphiql.js" charset="utf-8"></script>

</head>
<body>
<div id="graphiql">Loading...</div>
<script>

/**
* This GraphiQL example illustrates how to use some of GraphiQL's props
* in order to enable reading and updating the URL parameters, making
* link sharing of queries a little bit easier.
*
* This is only one example of this kind of feature, GraphiQL exposes
* various React params to enable interesting integrations.
*/

// Parse the search string to get url parameters.
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) {
// When working locally, the example expects a GraphQL server at the path /graphql.
// In a PR preview, it connects to the Star Wars API externally.
// Change this to point wherever you host your GraphQL server.
const isDev = !window.location.hostname.match(/(^|\.)netlify\.com$|(^|\.)graphql\.org$/)
const api = isDev ? '/api/graphql' : 'https://swapi.graph.cool/'
const token = localStorage.getItem('Authorization')
return fetch(api, {
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,
defaultVariableEditorOpen: true,
onEditOperationName: onEditOperationName
}),
document.getElementById('graphiql')
);
</script>
</body>
</html>

41 changes: 26 additions & 15 deletions examples/src/main/scala/caliban/ExampleApp.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ package caliban

import caliban.ExampleData._
import caliban.GraphQL._
import caliban.schema.Annotations.{ GQLDeprecated, GQLDescription }
import caliban.schema.Annotations.{GQLDeprecated, GQLDescription}
import caliban.schema.GenericSchema
import cats.data.Kleisli
import cats.effect.Blocker
import org.http4s.StaticFile
import org.http4s.implicits._
import org.http4s.server.Router
import org.http4s.server.blaze.BlazeServerBuilder
import org.http4s.server.middleware.CORS
import zio._
import zio.blocking.Blocking
import zio.clock.Clock
import zio.console.{ putStrLn, Console }
import zio.console.{Console, putStrLn}
import zio.interop.catz._
import zio.stream.ZStream

Expand All @@ -27,9 +31,9 @@ object ExampleApp extends CatsApp with GenericSchema[Console with Clock] {

type ExampleTask[A] = RIO[Console with Clock, A]

implicit val roleSchema = gen[Role]
implicit val characterSchema = gen[Character]
implicit val characterArgsSchema = gen[CharacterArgs]
implicit val roleSchema = gen[Role]
implicit val characterSchema = gen[Character]
implicit val characterArgsSchema = gen[CharacterArgs]
implicit val charactersArgsSchema = gen[CharactersArgs]

override def run(args: List[String]): ZIO[ZEnv, Nothing, Int] =
Expand All @@ -45,16 +49,23 @@ object ExampleApp extends CatsApp with GenericSchema[Console with Clock] {
Subscriptions(service.deletedEvents)
)
)
blocker <- ZIO
.accessM[Blocking](_.blocking.blockingExecutor.map(_.asEC))
.map(Blocker.liftExecutionContext)
_ <- BlazeServerBuilder[ExampleTask]
.bindHttp(8088, "localhost")
.withHttpApp(
Router(
"/api/graphql" -> CORS(Http4sAdapter.makeRestService(interpreter)),
"/ws/graphql" -> CORS(Http4sAdapter.makeWebSocketService(interpreter))
).orNotFound
)
.resource
.toManaged
.useForever
.bindHttp(8088, "localhost")
.withHttpApp(
Router[ExampleTask](
"/api/graphql" -> CORS(Http4sAdapter.makeRestService(interpreter)),
"/ws/graphql" -> CORS(
Http4sAdapter.makeWebSocketService(interpreter)
),
"/graphiql" -> Kleisli
.liftF(StaticFile.fromResource("/graphiql.html", blocker, None))
).orNotFound
)
.resource
.toManaged
.useForever
} yield 0).catchAll(err => putStrLn(err.toString).as(1))
}