这是indexloc提供的服务,不要输入任何密码
Skip to content
18 changes: 15 additions & 3 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package cli

import (
"bytes"
"net/url"
"os"
"path/filepath"
"regexp"
Expand Down Expand Up @@ -50,6 +51,18 @@ type HasuraGraphQLConfig struct {
Endpoint string `json:"endpoint"`
// AccessKey (optional) required to query the endpoint
AccessKey string `json:"access_key,omitempty"`

ParsedEndpoint *url.URL
}

// ParseEndpoint ensures the endpoint is valid.
func (hgc *HasuraGraphQLConfig) ParseEndpoint() error {
nurl, err := url.Parse(hgc.Endpoint)
if err != nil {
return err
}
hgc.ParsedEndpoint = nurl
return nil
}

// ExecutionContext contains various contextual information required by the cli
Expand Down Expand Up @@ -204,15 +217,14 @@ func (ec *ExecutionContext) readConfig() error {
v.AddConfigPath(ec.ExecutionDirectory)
err := v.ReadInConfig()
if err != nil {
ec.Logger.WithError(err).Error("cannot read config file")
return errors.Wrap(err, "cannor read config file")
}

ec.Config = &HasuraGraphQLConfig{
Endpoint: v.GetString("endpoint"),
AccessKey: v.GetString("access_key"),
}
return nil
err = ec.Config.ParseEndpoint()
return err
}

// setupSpinner creates a default spinner if the context does not already have
Expand Down
44 changes: 19 additions & 25 deletions cli/commands/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import (
"fmt"
"net/http"
"net/url"
"path/filepath"
"runtime"
"sync"

"github.com/fatih/color"
Expand All @@ -15,6 +13,7 @@ import (
"github.com/hasura/graphql-engine/cli/migrate/api"
"github.com/hasura/graphql-engine/cli/util"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/skratchdot/open-golang/open"
"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand Down Expand Up @@ -86,12 +85,7 @@ func (o *consoleOptions) run() error {
r,
}

u, err := url.Parse(o.EC.Config.Endpoint)
if err != nil {
return errors.Wrap(err, "cannot parse endpoint as url")
}

router.setRoutes(u.Host, o.EC.Config.AccessKey, o.EC.MigrationDir)
router.setRoutes(o.EC.Config.ParsedEndpoint, o.EC.Config.AccessKey, o.EC.MigrationDir, o.EC.Logger)

if o.EC.Version == nil {
return errors.New("cannot validate version, object is nil")
Expand All @@ -105,7 +99,7 @@ func (o *consoleOptions) run() error {
"apiHost": "http://" + o.Address,
"apiPort": o.APIPort,
"cliVersion": o.EC.Version.GetCLIVersion(),
"dataApiUrl": o.EC.Config.Endpoint,
"dataApiUrl": o.EC.Config.ParsedEndpoint.String(),
"dataApiVersion": "",
"accessKey": o.EC.Config.AccessKey,
"assetsVersion": consoleAssetsVersion,
Expand Down Expand Up @@ -158,14 +152,15 @@ type consoleRouter struct {
*gin.Engine
}

func (router *consoleRouter) setRoutes(host, accessKey, migrationDir string) {
func (router *consoleRouter) setRoutes(nurl *url.URL, accessKey, migrationDir string, logger *logrus.Logger) {
apis := router.Group("/apis")
{
apis.Use(setLogger(logger))
apis.Use(setFilePath(migrationDir))
apis.Use(setDataPath(nurl, accessKey))
// Migrate api endpoints and middleware
migrateAPIs := apis.Group("/migrate")
{
migrateAPIs.Use(setFilePath(migrationDir))
migrateAPIs.Use(setDataPath(host, accessKey))
settingsAPIs := migrateAPIs.Group("/settings")
{
settingsAPIs.Any("", api.SettingsAPI)
Expand All @@ -175,32 +170,31 @@ func (router *consoleRouter) setRoutes(host, accessKey, migrationDir string) {
// Migrate api endpoints and middleware
metadataAPIs := apis.Group("/metadata")
{
metadataAPIs.Use(setFilePath(migrationDir))
metadataAPIs.Use(setDataPath(host, accessKey))
metadataAPIs.Any("", api.MetadataAPI)
}
}
}

func setDataPath(hostName, accessKey string) gin.HandlerFunc {
func setDataPath(nurl *url.URL, accessKey string) gin.HandlerFunc {
return func(c *gin.Context) {
host := url.URL{
Scheme: "hasuradb",
User: url.UserPassword("admin", accessKey),
Host: hostName,
}
host := getDataPath(nurl, accessKey)

c.Set("dbpath", host)
c.Next()
}
}

func setFilePath(dir string) gin.HandlerFunc {
return func(c *gin.Context) {
if runtime.GOOS == "windows" {
c.Set("filedir", "file:///"+filepath.Clean(dir))
} else {
c.Set("filedir", "file://"+filepath.Clean(dir))
}
host := getFilePath(dir)
c.Set("filedir", host)
c.Next()
}
}

func setLogger(logger *logrus.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("logger", logger)
c.Next()
}
}
Expand Down
6 changes: 5 additions & 1 deletion cli/commands/console_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ func TestConsoleCmd(t *testing.T) {
DontOpenBrowser: true,
}
opts.EC.Spinner.Writer = &fake.FakeWriter{}
err := opts.EC.Config.ParseEndpoint()
if err != nil {
t.Fatal(err)
}

go func() {
t.Log("waiting for console to start")
Expand All @@ -38,7 +42,7 @@ func TestConsoleCmd(t *testing.T) {
opts.WG.Done()
opts.WG.Done()
}()
err := opts.run()
err = opts.run()
if err != nil {
t.Fatalf("failed running console: %v", err)
}
Expand Down
54 changes: 54 additions & 0 deletions cli/commands/metadata.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
package commands

import (
"encoding/json"
"io/ioutil"
"path/filepath"

"github.com/ghodss/yaml"
"github.com/hasura/graphql-engine/cli"
"github.com/hasura/graphql-engine/cli/migrate"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
Expand Down Expand Up @@ -31,3 +38,50 @@ func NewMetadataCmd(ec *cli.ExecutionContext) *cobra.Command {
v.BindPFlag("access_key", f.Lookup("access-key"))
return metadataCmd
}

func executeMetadata(cmd string, t *migrate.Migrate, metadata string) error {
switch cmd {
case "export":
metaData, err := t.ExportMetadata()
if err != nil {
return errors.Wrap(err, "Cannot export metadata")
}

t, err := json.Marshal(metaData)
if err != nil {
return errors.Wrap(err, "Cannot Marshal metadata")
}

data, err := yaml.JSONToYAML(t)
if err != nil {
return err
}

err = ioutil.WriteFile(filepath.Join(metadata, "metadata.yaml"), data, 0644)
if err != nil {
return errors.Wrap(err, "cannot save metadata")
}
case "reset":
err := t.ResetMetadata()
if err != nil {
return errors.Wrap(err, "Cannot reset Metadata")
}
case "apply":
data, err := ioutil.ReadFile(filepath.Join(metadata, "metadata.yaml"))
if err != nil {
return errors.Wrap(err, "cannot read metadata file")
}

var q interface{}
err = yaml.Unmarshal(data, &q)
if err != nil {
return errors.Wrap(err, "cannot parse metadata file")
}

err = t.ApplyMetadata(q)
if err != nil {
return errors.Wrap(err, "cannot apply metadata on the database")
}
}
return nil
}
13 changes: 3 additions & 10 deletions cli/commands/metadata_apply.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package commands

import (
"net/url"

"github.com/hasura/graphql-engine/cli"
"github.com/hasura/graphql-engine/cli/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -36,12 +32,9 @@ type metadataApplyOptions struct {
}

func (o *metadataApplyOptions) run() error {
dbURL, err := url.Parse(o.EC.Config.Endpoint)
migrateDrv, err := newMigrate(o.EC.MigrationDir, o.EC.Config.ParsedEndpoint, o.EC.Config.AccessKey, o.EC.Logger)
if err != nil {
return errors.Wrap(err, "error parsing Endpoint")
return err
}

dbURL.Scheme = "hasuradb"
dbURL.User = url.UserPassword("admin", o.EC.Config.AccessKey)
return util.ExecuteMetadata(o.actionType, "file://"+o.EC.MigrationDir, dbURL.String(), o.EC.ExecutionDirectory)
return executeMetadata(o.actionType, migrateDrv, o.EC.ExecutionDirectory)
}
8 changes: 5 additions & 3 deletions cli/commands/metadata_apply_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package commands

import (
"net/url"
"testing"
"time"

Expand All @@ -9,16 +10,17 @@ import (
"github.com/sirupsen/logrus/hooks/test"
)

func testMetadataApply(t *testing.T, executionDir string, endpoint string) {
func testMetadataApply(t *testing.T, executionDir string, endpoint *url.URL) {
logger, _ := test.NewNullLogger()
opts := &metadataApplyOptions{
EC: &cli.ExecutionContext{
Logger: logger,
Spinner: spinner.New(spinner.CharSets[7], 100*time.Millisecond),
ExecutionDirectory: executionDir,
Config: &cli.HasuraGraphQLConfig{
Endpoint: endpoint,
AccessKey: "",
Endpoint: endpoint.String(),
AccessKey: "",
ParsedEndpoint: endpoint,
},
},
actionType: "apply",
Expand Down
13 changes: 3 additions & 10 deletions cli/commands/metadata_export.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package commands

import (
"net/url"

"github.com/hasura/graphql-engine/cli"
"github.com/hasura/graphql-engine/cli/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -36,12 +32,9 @@ type metadataExportOptions struct {
}

func (o *metadataExportOptions) run() error {
dbURL, err := url.Parse(o.EC.Config.Endpoint)
migrateDrv, err := newMigrate(o.EC.MigrationDir, o.EC.Config.ParsedEndpoint, o.EC.Config.AccessKey, o.EC.Logger)
if err != nil {
return errors.Wrap(err, "error parsing Endpoint")
return err
}

dbURL.Scheme = "hasuradb"
dbURL.User = url.UserPassword("admin", o.EC.Config.AccessKey)
return util.ExecuteMetadata(o.actionType, "file://"+o.EC.MigrationDir, dbURL.String(), o.EC.ExecutionDirectory)
return executeMetadata(o.actionType, migrateDrv, o.EC.ExecutionDirectory)
}
8 changes: 5 additions & 3 deletions cli/commands/metadata_export_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package commands

import (
"net/url"
"testing"
"time"

Expand All @@ -9,16 +10,17 @@ import (
"github.com/sirupsen/logrus/hooks/test"
)

func testMetadataExport(t *testing.T, executionDir string, endpoint string) {
func testMetadataExport(t *testing.T, executionDir string, endpoint *url.URL) {
logger, _ := test.NewNullLogger()
opts := &metadataExportOptions{
EC: &cli.ExecutionContext{
Logger: logger,
Spinner: spinner.New(spinner.CharSets[7], 100*time.Millisecond),
ExecutionDirectory: executionDir,
Config: &cli.HasuraGraphQLConfig{
Endpoint: endpoint,
AccessKey: "",
Endpoint: endpoint.String(),
AccessKey: "",
ParsedEndpoint: endpoint,
},
},
actionType: "export",
Expand Down
12 changes: 3 additions & 9 deletions cli/commands/metadata_reset.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package commands

import (
"net/url"

"github.com/hasura/graphql-engine/cli"
"github.com/hasura/graphql-engine/cli/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
Expand Down Expand Up @@ -36,14 +33,11 @@ type metadataResetOptions struct {
}

func (o *metadataResetOptions) run() error {
dbURL, err := url.Parse(o.EC.Config.Endpoint)
migrateDrv, err := newMigrate(o.EC.MigrationDir, o.EC.Config.ParsedEndpoint, o.EC.Config.AccessKey, o.EC.Logger)
if err != nil {
return errors.Wrap(err, "error parsing Endpoint")
return err
}

dbURL.Scheme = "hasuradb"
dbURL.User = url.UserPassword("admin", o.EC.Config.AccessKey)
err = util.ExecuteMetadata(o.actionType, "file://"+o.EC.MigrationDir, dbURL.String(), o.EC.ExecutionDirectory)
err = executeMetadata(o.actionType, migrateDrv, o.EC.ExecutionDirectory)
if err != nil {
return errors.Wrap(err, "Cannot reset metadata")
}
Expand Down
Loading