graphqlconsole.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * EliasDB
  3. *
  4. * Copyright 2016 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the Mozilla Public
  7. * License, v. 2.0. If a copy of the MPL was not distributed with this
  8. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. */
  10. package console
  11. import (
  12. "encoding/json"
  13. "fmt"
  14. "devt.de/krotik/common/errorutil"
  15. v1 "devt.de/krotik/eliasdb/api/v1"
  16. )
  17. // GraphQL Console
  18. // ===============
  19. /*
  20. GraphQLConsole runs GraphQL queries.
  21. */
  22. type GraphQLConsole struct {
  23. parent CommandConsoleAPI // Parent console API
  24. }
  25. /*
  26. graphQLConsoleKeywords are all keywords which this console can process.
  27. */
  28. var graphQLConsoleKeywords = []string{"{", "query", "mutation"}
  29. /*
  30. Run executes one or more commands. It returns an error if the command
  31. had an unexpected result and a flag if the command was handled.
  32. */
  33. func (c *GraphQLConsole) Run(cmd string) (bool, error) {
  34. if !cmdStartsWithKeyword(cmd, graphQLConsoleKeywords) {
  35. return false, nil
  36. }
  37. q, err := json.Marshal(map[string]interface{}{
  38. "operationName": nil,
  39. "variables": nil,
  40. "query": cmd,
  41. })
  42. errorutil.AssertOk(err)
  43. resObj, err := c.parent.Req(
  44. fmt.Sprintf("%s%s", v1.EndpointGraphQL, c.parent.Partition()), "POST", q)
  45. if err == nil && resObj != nil {
  46. actualResultBytes, _ := json.MarshalIndent(resObj, "", " ")
  47. out := string(actualResultBytes)
  48. c.parent.ExportBuffer().WriteString(out)
  49. fmt.Fprint(c.parent.Out(), out)
  50. }
  51. return true, err
  52. }
  53. /*
  54. Commands returns an empty list. The command line is interpreted as a GraphQL query.
  55. */
  56. func (c *GraphQLConsole) Commands() []Command {
  57. return nil
  58. }