-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathextension.go
242 lines (199 loc) · 5.25 KB
/
extension.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright (c) Liam Stanley <liam@liam.sh>. All rights reserved. Use of
// this source code is governed by the MIT license that can be found in
// the LICENSE file.
package entrest
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"entgo.io/ent/entc"
"entgo.io/ent/entc/gen"
"github.com/ogen-go/ogen"
)
// Ensure that Extension implements the entc.Extension interface.
var _ entc.Extension = (*Extension)(nil)
type Extension struct {
entc.DefaultExtension
config *Config
}
func NewExtension(config *Config) (*Extension, error) {
if config == nil {
config = &Config{}
}
if err := config.Validate(); err != nil {
return nil, err
}
return &Extension{config: config}, nil
}
func (e *Extension) Templates() []*gen.Template {
if e.config.Handler == HandlerNone {
return []*gen.Template{}
}
return append([]*gen.Template{baseTemplates, testingTemplates}, e.config.Templates...)
}
func (e *Extension) Hooks() []gen.Hook {
return []gen.Hook{
func(next gen.Generator) gen.Generator {
return gen.GenerateFunc(func(g *gen.Graph) error {
if !e.config.DisablePatchJSONTag {
err := patchJSONTag(g)
if err != nil {
return err
}
}
return next.Generate(g)
})
},
func(next gen.Generator) gen.Generator {
return gen.GenerateFunc(func(g *gen.Graph) error {
spec, err := e.Generate(g)
if err != nil {
return err
}
err = e.writeSpec(g, spec)
if err != nil {
return err
}
return next.Generate(g)
})
},
}
}
func (e *Extension) Generate(g *gen.Graph) (*ogen.Spec, error) {
// Validate all annotations first.
err := ValidateAnnotations(g.Nodes...)
if err != nil {
return nil, fmt.Errorf("failed to validate annotations: %w", err)
}
spec := e.config.Spec
if spec == nil {
if e.config.SpecFromPath != "" {
var f *os.File
f, err = os.Open(e.config.SpecFromPath)
if err != nil {
return nil, fmt.Errorf("failed to open spec from path %q: %w", e.config.SpecFromPath, err)
}
spec = ogen.NewSpec()
dec := json.NewDecoder(f)
err = dec.Decode(spec)
if err != nil {
f.Close()
return nil, fmt.Errorf("failed to decode spec from path %q: %w", e.config.SpecFromPath, err)
}
f.Close()
} else {
spec = ogen.NewSpec()
}
}
if e.config.PreGenerateHook != nil {
err = e.config.PreGenerateHook(g, spec)
if err != nil {
return nil, err
}
}
// If they weren't provided, set some defaults which are required by OpenAPI,
// as well as most code-generators.
if spec.OpenAPI == "" {
spec.OpenAPI = OpenAPIVersion
}
if spec.Info.Title == "" {
spec.Info.Title = "EntGo Rest API"
}
if spec.Info.Version == "" {
spec.Info.Version = "1.0.0"
}
var specs []*ogen.Spec
var tspec *ogen.Spec
var ops []Operation
for _, t := range g.Nodes {
ta := GetAnnotation(t)
if ta.GetSkip(e.config) {
continue
}
ops = ta.GetOperations(e.config)
for _, op := range ops {
if t.ID == nil && (op != OperationList && op != OperationCreate) {
continue
}
tspec, err = GetSpecType(t, op)
if err != nil {
panic(err)
}
specs = append(specs, tspec)
}
if t.ID == nil {
continue
}
for _, edge := range t.Edges {
if edge.Type.ID == nil {
// It's a through-edge which has no individual ID, rather a composite ID,
// which likely shouldn't be queryable.
continue
}
ea := GetAnnotation(edge)
if ea.GetSkip(e.config) || !ea.GetEdgeEndpoint(e.config) {
continue
}
ops = ta.GetOperations(e.config)
if edge.Unique && slices.Contains(ops, OperationRead) {
tspec, err = GetSpecEdge(t, edge, OperationRead)
}
if !edge.Unique && slices.Contains(ops, OperationList) {
tspec, err = GetSpecEdge(t, edge, OperationList)
}
if err != nil {
panic(err)
}
specs = append(specs, tspec)
}
}
if !e.config.DisableSpecHandler {
specs = append(specs, addOpenAPIEndpoint("/openapi.json"))
}
err = MergeSpecOverlap(spec, specs...)
if err != nil {
panic(err)
}
if (!e.config.DisableSpecHandler && len(spec.Paths) == 1) || (e.config.DisableSpecHandler && len(spec.Paths) == 0) {
return nil, errors.New("spec generated no operations, thus no spec paths can be generated")
}
if e.config.PostGenerateHook != nil {
err = e.config.PostGenerateHook(g, spec)
if err != nil {
return nil, err
}
}
addGlobalErrorResponses(e.config, spec, e.config.GlobalErrorResponses)
addGlobalRequestHeaders(spec, e.config.GlobalRequestHeaders)
addGlobalResponseHeaders(spec, e.config.GlobalResponseHeaders)
return spec, nil
}
func (e *Extension) writeSpec(g *gen.Graph, spec *ogen.Spec) error {
if e.config.PreWriteHook != nil {
if err := e.config.PreWriteHook(spec); err != nil {
return err
}
}
if e.config.Writer == nil {
dir := filepath.Join(g.Target, "rest")
err := os.MkdirAll(dir, 0o750)
if err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
f, err := os.OpenFile(filepath.Join(dir, "openapi.json"), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o640)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer f.Close()
e.config.Writer = f
}
enc := json.NewEncoder(e.config.Writer)
enc.SetIndent("", " ")
return enc.Encode(spec)
}
func (e *Extension) Annotations() []entc.Annotation {
return []entc.Annotation{e.config}
}