graphql.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 dbfunc
  11. import (
  12. "fmt"
  13. "devt.de/krotik/ecal/parser"
  14. "devt.de/krotik/ecal/scope"
  15. "devt.de/krotik/eliasdb/graph"
  16. "devt.de/krotik/eliasdb/graphql"
  17. )
  18. /*
  19. GraphQLFunc runs a GraphQL query.
  20. */
  21. type GraphQLFunc struct {
  22. GM *graph.Manager
  23. }
  24. /*
  25. Run executes the ECAL function.
  26. */
  27. func (f *GraphQLFunc) Run(instanceID string, vs parser.Scope, is map[string]interface{}, tid uint64, args []interface{}) (interface{}, error) {
  28. var err error
  29. var ret interface{}
  30. if arglen := len(args); arglen < 2 {
  31. err = fmt.Errorf("Function requires at least 2 parameters: partition and query with optionally a map of variables and an operation name")
  32. }
  33. if err == nil {
  34. var res, varMap map[string]interface{}
  35. part := fmt.Sprint(args[0])
  36. query := fmt.Sprint(args[1])
  37. opname := ""
  38. if err == nil && len(args) > 2 {
  39. varECALMap, ok := args[2].(map[interface{}]interface{})
  40. if !ok {
  41. err = fmt.Errorf("Third parameter must be a map")
  42. } else {
  43. varMap = make(map[string]interface{})
  44. for k, v := range varECALMap {
  45. varMap[fmt.Sprint(k)] = v
  46. }
  47. }
  48. }
  49. if err == nil && len(args) > 3 {
  50. opname = fmt.Sprint(args[3])
  51. }
  52. if err == nil {
  53. res, err = graphql.RunQuery("db.query", part, map[string]interface{}{
  54. "operationName": opname,
  55. "query": query,
  56. "variables": varMap,
  57. }, f.GM, nil, false)
  58. if err == nil {
  59. ret = scope.ConvertJSONToECALObject(res)
  60. }
  61. }
  62. }
  63. return ret, err
  64. }
  65. /*
  66. DocString returns a descriptive string.
  67. */
  68. func (f *GraphQLFunc) DocString() (string, error) {
  69. return "Run a GraphQL query.", nil
  70. }