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

added playground #37

Merged
merged 1 commit into from
Jul 2, 2018
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,16 @@ func main() {
}
```

### Using Playground
```go
h := handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: false,
Playground: true,
})
```

### Details

The handler will accept requests with
Expand Down
109 changes: 109 additions & 0 deletions graphcoolPlayground.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package handler

import (
"fmt"
"html/template"
"net/http"
)

type playgroundData struct {
PlaygroundVersion string
Endpoint string
SubscriptionEndpoint string
SetTitle bool
}

// renderPlayground renders the Playground GUI
func renderPlayground(w http.ResponseWriter, r *http.Request) {
t := template.New("Playground")
t, err := t.Parse(graphcoolPlaygroundTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

d := playgroundData{
PlaygroundVersion: graphcoolPlaygroundVersion,
Endpoint: "/graphql",
SubscriptionEndpoint: fmt.Sprintf("ws://%v/subscriptions", r.Host),
SetTitle: true,
}
err = t.ExecuteTemplate(w, "index", d)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}

return
}

const graphcoolPlaygroundVersion = "1.5.2"

const graphcoolPlaygroundTemplate = `
{{ define "index" }}
<!--
The request to this GraphQL server provided the header "Accept: text/html"
and as a result has been presented Playground - an in-browser IDE for
exploring GraphQL.

If you wish to receive JSON, provide the header "Accept: application/json" or
add "&raw" to the end of the URL within a browser.
-->
<!DOCTYPE html>
<html>

<head>
<meta charset=utf-8/>
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<title>GraphQL Playground</title>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/graphql-playground-react/build/static/css/index.css" />
<link rel="shortcut icon" href="//cdn.jsdelivr.net/npm/graphql-playground-react/build/favicon.png" />
<script src="//cdn.jsdelivr.net/npm/graphql-playground-react/build/static/js/middleware.js"></script>
</head>

<body>
<div id="root">
<style>
body {
background-color: rgb(23, 42, 58);
font-family: Open Sans, sans-serif;
height: 90vh;
}
#root {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.loading {
font-size: 32px;
font-weight: 200;
color: rgba(255, 255, 255, .6);
margin-left: 20px;
}
img {
width: 78px;
height: 78px;
}
.title {
font-weight: 400;
}
</style>
<img src='//cdn.jsdelivr.net/npm/graphql-playground-react/build/logo.png' alt=''>
<div class="loading"> Loading
<span class="title">GraphQL Playground</span>
</div>
</div>
<script>window.addEventListener('load', function (event) {
GraphQLPlayground.init(document.getElementById('root'), {
// options as 'endpoint' belong here
endpoint: {{ .Endpoint }},
subscriptionEndpoint: {{ .SubscriptionEndpoint }},
setTitle: {{ .SetTitle }}
})
})</script>
</body>

</html>
{{ end }}
`
91 changes: 91 additions & 0 deletions graphcoolPlayground_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package handler_test

import (
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/graphql-go/graphql/testutil"
"github.com/graphql-go/handler"
)

func TestRenderPlayground(t *testing.T) {
cases := map[string]struct {
playgroundEnabled bool
accept string
url string
expectedStatusCode int
expectedContentType string
expectedBodyContains string
}{
"renders Playground": {
playgroundEnabled: true,
accept: "text/html",
expectedStatusCode: http.StatusOK,
expectedContentType: "text/html; charset=utf-8",
expectedBodyContains: "<!DOCTYPE html>",
},
"doesn't render Playground if turned off": {
playgroundEnabled: false,
accept: "text/html",
expectedStatusCode: http.StatusOK,
expectedContentType: "application/json; charset=utf-8",
},
"doesn't render Playground if Content-Type application/json is present": {
playgroundEnabled: true,
accept: "application/json,text/html",
expectedStatusCode: http.StatusOK,
expectedContentType: "application/json; charset=utf-8",
},
"doesn't render Playground if Content-Type text/html is not present": {
playgroundEnabled: true,
expectedStatusCode: http.StatusOK,
expectedContentType: "application/json; charset=utf-8",
},
"doesn't render Playground if 'raw' query is present": {
playgroundEnabled: true,
accept: "text/html",
url: "?raw",
expectedStatusCode: http.StatusOK,
expectedContentType: "application/json; charset=utf-8",
},
}

for tcID, tc := range cases {
t.Run(tcID, func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, tc.url, nil)
if err != nil {
t.Error(err)
}

req.Header.Set("Accept", tc.accept)

h := handler.New(&handler.Config{
Schema: &testutil.StarWarsSchema,
GraphiQL: false,
Playground: tc.playgroundEnabled,
})

rr := httptest.NewRecorder()

h.ServeHTTP(rr, req)
resp := rr.Result()

statusCode := resp.StatusCode
if statusCode != tc.expectedStatusCode {
t.Fatalf("%s: wrong status code, expected %v, got %v", tcID, tc.expectedStatusCode, statusCode)
}

contentType := resp.Header.Get("Content-Type")
if contentType != tc.expectedContentType {
t.Fatalf("%s: wrong content type, expected %s, got %s", tcID, tc.expectedContentType, contentType)
}

body := rr.Body.String()
if !strings.Contains(body, tc.expectedBodyContains) {
t.Fatalf("%s: wrong body, expected %s to contain %s", tcID, body, tc.expectedBodyContains)
}
})
}
}
37 changes: 25 additions & 12 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ const (
)

type Handler struct {
Schema *graphql.Schema
pretty bool
graphiql bool
Schema *graphql.Schema
pretty bool
graphiql bool
playground bool
}
type RequestOptions struct {
Query string `json:"query" url:"query" schema:"query"`
Expand Down Expand Up @@ -138,6 +139,15 @@ func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *
}
}

if h.playground {
acceptHeader := r.Header.Get("Accept")
_, raw := r.URL.Query()["raw"]
if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
renderPlayground(w, r)
return
}
}

// use proper JSON Header
w.Header().Add("Content-Type", "application/json; charset=utf-8")

Expand All @@ -160,16 +170,18 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

type Config struct {
Schema *graphql.Schema
Pretty bool
GraphiQL bool
Schema *graphql.Schema
Pretty bool
GraphiQL bool
Playground bool
}

func NewConfig() *Config {
return &Config{
Schema: nil,
Pretty: true,
GraphiQL: true,
Schema: nil,
Pretty: true,
GraphiQL: true,
Playground: false,
}
}

Expand All @@ -182,8 +194,9 @@ func New(p *Config) *Handler {
}

return &Handler{
Schema: p.Schema,
pretty: p.Pretty,
graphiql: p.GraphiQL,
Schema: p.Schema,
pretty: p.Pretty,
graphiql: p.GraphiQL,
playground: p.Playground,
}
}