/
template.go
215 lines (176 loc) · 5.7 KB
/
template.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package generator
import "text/template"
var dataloadersTemplate = template.Must(template.New("generated").
Funcs(template.FuncMap{
"lcFirst": lcFirst,
}).
Parse(`
// Code generated by github.com/mikeydub/go-gallery/cmd/dataloaders, DO NOT EDIT.
package {{.Package}}
import (
"sync"
"time"
"context"
"github.com/mikeydub/go-gallery/cmd/dataloaders/generator"
{{range .ImportPaths}}
"{{.}}"
{{end}}
)
type autoCacheWithKey[TKey any, TResult any] interface {
getKeyForResult(TResult) TKey
}
type autoCacheWithKeys[TKey any, TResult any] interface {
getKeysForResult(TResult) []TKey
}
type notFoundErrorProvider[TKey any] interface {
getNotFoundError(TKey) error
}
type PreFetchHook func(context.Context, string) context.Context
type PostFetchHook func(context.Context, string)
{{range .Definitions}}
// {{.Name}} batches and caches requests
type {{.Name}} struct {
generator.Dataloader[{{.KeyType.String}}, {{.ResultType.String}}]
}
// new{{.Name}} creates a new {{.Name}} with the given settings, functions, and options
func new{{.Name}}(
ctx context.Context,
maxBatchSize int,
batchTimeout time.Duration,
cacheResults bool,
publishResults bool,
fetch func(context.Context, *{{.Name}}, []{{.KeyType.String}}) ([]{{.ResultType.String}}, []error),
preFetchHook PreFetchHook,
postFetchHook PostFetchHook,
) *{{.Name}} {
d := &{{.Name}}{}
fetchWithHooks := func(ctx context.Context, keys []{{.KeyType.String}}) ([]{{.ResultType.String}}, []error) {
// Allow the preFetchHook to modify and return a new context
if preFetchHook != nil {
ctx = preFetchHook(ctx, "{{.Name}}")
}
results, errors := fetch(ctx, d, keys)
if postFetchHook != nil {
postFetchHook(ctx, "{{.Name}}")
}
return results, errors
}
{{ if .KeyIsComparable }}
d.Dataloader = *generator.NewDataloader(ctx, maxBatchSize, batchTimeout, cacheResults, publishResults, fetchWithHooks)
{{- else }}
d.Dataloader = *generator.NewDataloaderWithNonComparableKey(ctx, maxBatchSize, batchTimeout, cacheResults, publishResults, fetchWithHooks)
{{- end }}
return d
}
{{ if .CanAutoCacheDBID }}
func (*{{.Name}}) getKeyForResult(result {{.ResultType.String}}) persist.DBID {
return result.ID
}
{{- end }}
{{end}}
`))
var apiTemplate = template.Must(template.New("api").
Funcs(template.FuncMap{
"lcFirst": lcFirst,
}).
Parse(`
// Code generated by github.com/mikeydub/go-gallery/cmd/dataloaders, DO NOT EDIT.
package {{.Package}}
import (
"time"
"context"
"github.com/jackc/pgx/v4"
{{range .ImportPaths}}
"{{.}}"
{{end}}
)
type Loaders struct {
{{range .Definitions}}
{{.Name}} *{{.Name}}
{{- end}}
}
func NewLoaders(ctx context.Context, q *coredb.Queries, disableCaching bool, preFetchHook PreFetchHook, postFetchHook PostFetchHook) *Loaders {
loaders := &Loaders{}
{{range .Definitions}}
loaders.{{.Name}} = new{{.Name}}(ctx, {{.MaxBatchSize}}, time.Duration({{.BatchTimeout}}), !disableCaching, {{.PublishResults}}, load{{.Name}}(q), preFetchHook, postFetchHook)
{{- end}}
{{range .Subscriptions}}
{{- if .SingleKey }}
loaders.{{.Target}}.RegisterResultSubscriber(func(result {{.Result}}) {
{{- if .ResultIsSlice }}
for _, entry := range result {
loaders.{{.Subscriber}}.Prime(loaders.{{.Subscriber}}.getKeyForResult(entry{{.Field}}), entry{{.Field}})
}
{{- else }}
loaders.{{.Subscriber}}.Prime(loaders.{{.Subscriber}}.getKeyForResult(result{{.Field}}), result{{.Field}})
{{- end }}
})
{{- end }}
{{- if .ManyKeys }}
loaders.{{.Target}}.RegisterResultSubscriber(func(result {{.Result}}) {
{{- if .ResultIsSlice }}
for _, entry := range result {
for _, key := range loaders.{{.Subscriber}}.getKeysForResult(entry{{.Field}}) {
loaders.{{.Subscriber}}.Prime(key, entry{{.Field}})
}
}
{{- else }}
for _, key := range loaders.{{.Subscriber}}.getKeysForResult(result{{.Field}}) {
loaders.{{.Subscriber}}.Prime(key, result{{.Field}})
}
{{- end }}
})
{{- end }}
{{- end }}
return loaders
}
{{range .Definitions}}
{{ if .IsCustomBatch }}
func load{{.Name}}(q *coredb.Queries) func(context.Context, *{{.Name}}, []{{.KeyType.String}}) ([]{{.CustomBatching.LoaderResultType.String}}, []error) {
return func(ctx context.Context, d *{{.Name}}, params []{{.KeyType.String}}) ([]{{.CustomBatching.LoaderResultType.String}}, []error) {
queryResults, err := q.{{.Name}}(ctx, params)
results := make([]{{.CustomBatching.LoaderResultType.String}}, len(params))
errors := make([]error, len(params))
if err != nil {
for i := range errors {
errors[i] = err
}
return results, errors
}
hasResults := make([]bool, len(params))
for _, result := range queryResults {
results[result.{{.CustomBatching.BatchKeyIndexFieldName}}-1] = result{{.CustomBatching.ResultFieldName}}
hasResults[result.{{.CustomBatching.BatchKeyIndexFieldName}}-1] = true
}
for i, hasResult := range hasResults {
if !hasResult {
errors[i] = d.getNotFoundError(params[i])
}
}
return results, errors
}
}
{{ else }}
func load{{.Name}}(q *coredb.Queries) func(context.Context, *{{.Name}}, []{{.KeyType.String}}) ([]{{.ResultType.String}}, []error) {
return func(ctx context.Context, d *{{.Name}}, params []{{.KeyType.String}}) ([]{{.ResultType.String}}, []error) {
results := make([]{{.ResultType.String}}, len(params))
errors := make([]error, len(params))
b := q.{{.Name}}(ctx, params)
defer b.Close()
{{ if .ResultType.IsSlice }}
b.Query(func(i int, r {{.ResultType.String}}, err error) {
results[i], errors[i] = r, err
{{- else }}
b.QueryRow(func(i int, r {{.ResultType.String}}, err error) {
results[i], errors[i] = r, err
if errors[i] == pgx.ErrNoRows {
errors[i] = d.getNotFoundError(params[i])
}
{{- end }}
})
return results, errors
}
}
{{end}}
{{- end}}
`))