Skip to content

Consider exposing minimal static playground #66

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

Merged
merged 5 commits into from
Apr 28, 2020
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
31 changes: 29 additions & 2 deletions cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ import (
log2 "log"
"net/http"
"os"
"path"
"strings"
)

const defaultGraphQLPath = "/graphql"
const defaultGraphQLSchemaPath = "/graphql-schema"
const defaultRESTPath = "/todo"
const defaultGraphQLPlaygroundPath = "/graphql-playground"

// Environment variables prefixed with "DATA_API_" can override settings e.g. "DATA_API_HOSTS"
const envVarPrefix = "data_api"
Expand All @@ -33,8 +35,6 @@ var serverCmd = &cobra.Command{
Use: os.Args[0] + " --hosts [HOSTS] [--start-graph|--start-rest] [OPTIONS]",
Short: "GraphQL and REST endpoints for Apache Cassandra",
Args: func(cmd *cobra.Command, args []string) error {
// TODO: Validate GraphQL/REST paths, should they be disjointed?

hosts := viper.GetStringSlice("hosts")
if len(hosts) == 0 {
return errors.New("hosts are required")
Expand Down Expand Up @@ -62,6 +62,10 @@ var serverCmd = &cobra.Command{
startREST := viper.GetBool("start-rest")

if graphqlPort == restPort {
if startGraphQL && startREST && viper.GetString("graphql-path") == viper.GetString("rest-path") {
logger.Fatal("graphql and rest paths can not be the same when using the same port")
}

router := createRouter()
endpointNames := ""
if startGraphQL {
Expand Down Expand Up @@ -124,6 +128,8 @@ func Execute() {
flags.Bool("start-graphql", true, "start the GraphQL endpoint")
flags.String("graphql-path", defaultGraphQLPath, "GraphQL endpoint path")
flags.String("graphql-schema-path", defaultGraphQLSchemaPath, "GraphQL schema management path")
flags.Bool("graphql-playground", true, "expose a GraphQL playground route")
flags.String("graphql-playground-path", defaultGraphQLPlaygroundPath, "path for the GraphQL playground static file")
flags.Int("graphql-port", 8080, "GraphQL endpoint port")

// TODO:
Expand Down Expand Up @@ -208,6 +214,27 @@ func addGraphQLRoutes(router *httprouter.Router, endpoint *endpoint.DataEndpoint
"error", err)
}

if viper.GetBool("graphql-playground") {
playgroundPath := viper.GetString("graphql-playground-path")
hostAndPort := fmt.Sprintf("http://localhost:%d", viper.GetInt("graphql-port"))
defaultPath := rootPath
if singleKeyspace == "" {
// For multi-keyspace mode, use /graphql/<any_keyspace> as default playground endpoint url
keyspaces, err := endpoint.Keyspaces()
if err != nil {
logger.Fatal("could not retrieve keyspaces", "error", err)
}

if len(keyspaces) > 0 {
defaultPath = path.Join(rootPath, keyspaces[0])
}
}
defaultEndpointUrl := fmt.Sprintf("%s%s", hostAndPort, defaultPath)
logger.Info("get started by visiting the GraphQL playground",
"url", fmt.Sprintf("%s%s", hostAndPort, playgroundPath))
router.GET(playgroundPath, graphql.GetPlaygroundHandle(defaultEndpointUrl))
}

for _, route := range routes {
router.Handler(route.Method, route.Pattern, route.Handler)
}
Expand Down
5 changes: 5 additions & 0 deletions endpoint/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,8 @@ func (e *DataEndpoint) RoutesKeyspaceGraphQL(pattern string, ksName string) ([]g
func (e *DataEndpoint) RoutesSchemaManagementGraphQL(pattern string, ops config.SchemaOperations) ([]graphql.Route, error) {
return e.graphQLRouteGen.RoutesSchemaManagement(pattern, ops)
}

// Keyspaces gets a slice of keyspace names that are considered by the endpoint when used in multi-keyspace mode.
func (e *DataEndpoint) Keyspaces() ([]string, error) {
return e.graphQLRouteGen.Keyspaces()
}
74 changes: 74 additions & 0 deletions graphql/playground.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package graphql

import (
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
)

func GetPlaygroundHandle(defaultEndpointUrl string) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
html := `
<!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/[email protected]/build/static/css/index.css" />
<link rel="shortcut icon" href="//cdn.jsdelivr.net/npm/[email protected]/build/favicon.png" />
<script src="//cdn.jsdelivr.net/npm/[email protected]/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/[email protected]/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'), {
endpoint: '%s'
})
})</script>
</body>

</html>
`
html = fmt.Sprintf(html, defaultEndpointUrl)
fmt.Fprint(w, html)
}
}
18 changes: 18 additions & 0 deletions graphql/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,24 @@ func (rg *RouteGenerator) Routes(pattern string, singleKeyspace string) ([]Route
}), nil
}

// Keyspaces gets a slice of keyspace names that are considered by the route generator.
func (rg *RouteGenerator) Keyspaces() ([]string, error) {
keyspaces, err := rg.dbClient.Keyspaces()

if err != nil {
return nil, err
}

result := make([]string, 0, len(keyspaces))
for _, ksName := range keyspaces {
if !rg.schemaGen.isKeyspaceExcluded(ksName) {
result = append(result, ksName)
}
}

return result, nil
}

func getPathParser(root string) func(string) string {
if !strings.HasSuffix(root, "/") {
root += "/"
Expand Down