-
Notifications
You must be signed in to change notification settings - Fork 6
/
schema_builder.go
99 lines (79 loc) · 2.41 KB
/
schema_builder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package straf
import (
"reflect"
"github.com/graphql-go/graphql"
)
type middlewareType func(func(graphql.ResolveParams) (interface{}, error), graphql.ResolveParams) (interface{}, error)
// NewSchemaBuilder is used get a new schema builder
func NewSchemaBuilder(
graphQLType graphql.Output,
object interface{},
middlewareArg ...middlewareType) *SchemaBuilder {
var middleware middlewareType
if middlewareArg != nil {
middleware = middlewareArg[0]
}
builder := SchemaBuilder{
GraphQLType: graphQLType,
Object: object,
middleware: middleware,
}
builder.Init()
return &builder
}
// SchemaBuilder is used to build a schema based on a struct
type SchemaBuilder struct {
GraphQLType graphql.Output
Object interface{}
Schema graphql.Fields
args graphql.FieldConfigArgument
middleware middlewareType
}
// Init initializes
func (schemaBuilder *SchemaBuilder) Init() {
schemaBuilder.args = graphql.FieldConfigArgument{}
schemaBuilder.AddArgumentsFromStruct(schemaBuilder.Object)
schemaBuilder.Schema = graphql.Fields{}
}
//AddArgumentsFromStruct is used to add arguments from a struct
func (schemaBuilder *SchemaBuilder) AddArgumentsFromStruct(object interface{}) {
for key, value := range getArgs(object) {
schemaBuilder.args[key] = value
}
}
// AddFunction adds a function
func (schemaBuilder *SchemaBuilder) AddFunction(
name,
description string,
function func(graphql.ResolveParams) (interface{}, error)) {
var functionToAdd func(graphql.ResolveParams) (interface{}, error)
if schemaBuilder.middleware != nil {
functionToAdd = func(params graphql.ResolveParams) (interface{}, error) {
return schemaBuilder.middleware(function, params)
}
} else {
functionToAdd = function
}
schemaBuilder.Schema[name] = &graphql.Field{
Type: schemaBuilder.GraphQLType,
Description: description,
Args: schemaBuilder.args,
Resolve: functionToAdd,
}
}
func getArgs(object interface{}) graphql.FieldConfigArgument {
objectType := reflect.TypeOf(object)
output := graphql.FieldConfigArgument{}
for i := 0; i < objectType.NumField(); i++ {
currentField := objectType.Field(i)
identifier, ok := currentField.Tag.Lookup("isArg")
if identifier == "true" && ok {
fieldType := getFieldType(currentField)
output[currentField.Name] = &graphql.ArgumentConfig{
Type: fieldType,
Description: getTagValue(currentField, "description"),
}
}
}
return output
}