/
api_config.go
82 lines (70 loc) · 1.9 KB
/
api_config.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
package config
import (
"log"
"strings"
"github.com/gin-gonic/gin"
"github.com/goboilerplates/core"
"github.com/goboilerplates/micro-graphql/api"
"github.com/graphql-go/graphql"
)
var schema, _ = CreateSchema()
// SetAPIPaths sets API paths.
func SetAPIPaths(router *gin.Engine) gin.IRoutes {
routes := router.GET("/api", HanldeAPIRequest)
routes = router.POST("/api", HanldeAPIPOSTRequest)
return routes
}
// CreateSchema .
func CreateSchema() (graphql.Schema, error) {
var getSamplesAPI api.GetSamplesAPI
// inject GetSamplesAPIImpl .
getSamplesAPI = api.GetSamplesAPIImpl{
Interactor: core.CreateDefaultGetSamples("Kaka", "Ronaldo"),
}
sampleObject := api.GetSampleType()
fields := graphql.Fields{
"samples": &graphql.Field{
Type: graphql.NewList(sampleObject),
Args: graphql.FieldConfigArgument{
"keyword": &graphql.ArgumentConfig{
Type: graphql.String,
},
},
Resolve: getSamplesAPI.All,
},
}
rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
return graphql.NewSchema(schemaConfig)
}
// HanldeAPIRequest .
func HanldeAPIRequest(context *gin.Context) {
query := context.Query("query")
log.Println("request with query: ", query)
result := ExecuteQuery(query)
if len(result.Errors) > 0 {
context.JSON(404, result.Errors[0])
return
}
context.JSON(200, result.Data)
}
// HanldeAPIPOSTRequest .
func HanldeAPIPOSTRequest(context *gin.Context) {
data, _ := context.GetRawData()
query := string(data)
query = strings.Split(query, "=")[1]
log.Println("request with query: ", query)
result := ExecuteQuery(query)
if len(result.Errors) > 0 {
context.JSON(404, result.Errors[0])
return
}
context.JSON(200, result.Data)
}
// ExecuteQuery .
func ExecuteQuery(query string) *graphql.Result {
return graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
}