forked from wundergraph/graphql-go-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.go
99 lines (77 loc) · 2.32 KB
/
gateway.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 main
import (
"context"
"net/http"
"sync"
log "github.com/jensneuse/abstractlogger"
graphqlDataSource "github.com/dchukmasov/graphql-go-tools/v2/pkg/engine/datasource/graphql_datasource"
"github.com/dchukmasov/graphql-go-tools/v2/pkg/graphql"
)
type DataSourceObserver interface {
UpdateDataSources(dataSourceConfig []graphqlDataSource.Configuration)
}
type DataSourceSubject interface {
Register(observer DataSourceObserver)
}
type HandlerFactory interface {
Make(schema *graphql.Schema, engine *graphql.ExecutionEngineV2) http.Handler
}
type HandlerFactoryFn func(schema *graphql.Schema, engine *graphql.ExecutionEngineV2) http.Handler
func (h HandlerFactoryFn) Make(schema *graphql.Schema, engine *graphql.ExecutionEngineV2) http.Handler {
return h(schema, engine)
}
func NewGateway(
gqlHandlerFactory HandlerFactory,
httpClient *http.Client,
logger log.Logger,
) *Gateway {
return &Gateway{
gqlHandlerFactory: gqlHandlerFactory,
httpClient: httpClient,
logger: logger,
mu: &sync.Mutex{},
readyCh: make(chan struct{}),
readyOnce: &sync.Once{},
}
}
type Gateway struct {
gqlHandlerFactory HandlerFactory
httpClient *http.Client
logger log.Logger
gqlHandler http.Handler
mu *sync.Mutex
readyCh chan struct{}
readyOnce *sync.Once
}
func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
g.mu.Lock()
handler := g.gqlHandler
g.mu.Unlock()
handler.ServeHTTP(w, r)
}
func (g *Gateway) Ready() {
<-g.readyCh
}
func (g *Gateway) UpdateDataSources(newDataSourcesConfig []graphqlDataSource.Configuration) {
ctx := context.Background()
engineConfigFactory := graphql.NewFederationEngineConfigFactory(newDataSourcesConfig, graphql.WithFederationHttpClient(g.httpClient))
schema, err := engineConfigFactory.MergedSchema()
if err != nil {
g.logger.Error("get schema:", log.Error(err))
return
}
datasourceConfig, err := engineConfigFactory.EngineV2Configuration()
if err != nil {
g.logger.Error("get engine config: %v", log.Error(err))
return
}
engine, err := graphql.NewExecutionEngineV2(ctx, g.logger, datasourceConfig)
if err != nil {
g.logger.Error("create engine: %v", log.Error(err))
return
}
g.mu.Lock()
g.gqlHandler = g.gqlHandlerFactory.Make(schema, engine)
g.mu.Unlock()
g.readyOnce.Do(func() { close(g.readyCh) })
}