-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgenerator.go
423 lines (379 loc) · 12.6 KB
/
generator.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package reduxa
import (
"flag"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"text/template"
"time"
"github.com/goadesign/goa/design"
"github.com/goadesign/goa/goagen/codegen"
"github.com/goadesign/goa/goagen/utils"
"github.com/markbates/inflect"
)
// Generator is the application code generator.
type Generator struct {
genfiles []string // Generated files
outDir string // Destination directory
timeout time.Duration // Timeout used by JavaScript client when making requests
scheme string // Scheme used by JavaScript client
host string // Host addressed by JavaScript client
}
// Generate is the generator entry point called by the meta generator.
func Generate() (files []string, err error) {
var (
outDir string
timeout time.Duration
scheme, host, ver string
)
set := flag.NewFlagSet("reduxa", flag.PanicOnError)
set.StringVar(&outDir, "out", "", "")
set.String("design", "", "")
set.DurationVar(&timeout, "timeout", time.Duration(20)*time.Second, "")
set.StringVar(&scheme, "scheme", "", "")
set.StringVar(&host, "host", "", "")
set.StringVar(&ver, "version", "", "")
set.Parse(os.Args[2:])
// First check compatibility
if err := codegen.CheckVersion(ver); err != nil {
return nil, err
}
g := &Generator{outDir: outDir, timeout: timeout, scheme: scheme, host: host}
return g.Generate(design.Design)
}
// Generate produces the skeleton main.
func (g *Generator) Generate(api *design.APIDefinition) (_ []string, err error) {
go utils.Catch(nil, func() { g.Cleanup() })
defer func() {
if err != nil {
g.Cleanup()
}
}()
if g.scheme == "" && len(api.Schemes) > 0 {
g.scheme = api.Schemes[0]
}
if g.scheme == "" {
g.scheme = "http"
}
if g.host == "" {
g.host = api.Host
}
if g.host == "" {
return nil, fmt.Errorf("missing host value, set it with --host")
}
g.outDir = filepath.Join(g.outDir, api.Name)
if err := os.RemoveAll(g.outDir); err != nil {
return nil, err
}
if err := os.MkdirAll(g.outDir, 0755); err != nil {
return nil, err
}
g.genfiles = append(g.genfiles, g.outDir)
api.IterateResources(func(res *design.ResourceDefinition) error {
resourceName := baseName(res)
if resourceName == "" {
return nil
}
// Generate Redux action creators for this goa API
err = g.generateReduxActionCreators(filepath.Join(g.outDir, fmt.Sprint(resourceName, "ActionCreators.js")), api, res)
if err != nil {
return err
}
// Generate Redux action types for this goa API
err = g.generateReduxActionTypes(filepath.Join(g.outDir, fmt.Sprint(resourceName, "ActionTypes.js")), api, res)
if err != nil {
return err
}
// Generate Redux actions for this goa API
err = g.generateReduxActions(filepath.Join(g.outDir, fmt.Sprint(resourceName, "Actions.js")), api, res)
if err != nil {
return err
}
return nil
})
return g.genfiles, nil
}
func (g *Generator) generateReduxActionCreators(jsFile string, api *design.APIDefinition, res *design.ResourceDefinition) (err error) {
funcs := template.FuncMap{"params": params, "toUpper": strings.ToUpper, "resourceName": resourceName, "actionUnderResource": actionUnderResource}
file, err := codegen.SourceFileFor(jsFile)
if err != nil {
return
}
g.genfiles = append(g.genfiles, jsFile)
if res == nil {
return
}
data := map[string]interface{}{
"API": api,
"BaseName": baseName(res),
}
if err = file.ExecuteTemplate("beginActionCreators", beginActionCreatorsT, funcs, data); err != nil {
return
}
actions := make(map[string][]*design.ActionDefinition)
res.IterateActions(func(action *design.ActionDefinition) error {
if as, ok := actions[action.Name]; ok {
actions[action.Name] = append(as, action)
} else {
actions[action.Name] = []*design.ActionDefinition{action}
}
return nil
})
keys := []string{}
for n := range actions {
keys = append(keys, n)
}
sort.Strings(keys)
for _, n := range keys {
Actions:
for _, a := range actions[n] {
for _, scheme := range a.Schemes {
if scheme == "ws" {
continue Actions
}
}
data := map[string]interface{}{
"Action": a,
"API": api,
"Host": g.host,
"Scheme": g.scheme,
"Timeout": int64(g.timeout / time.Millisecond),
"ResourceName": actionResourceName(res, a),
}
if err = file.ExecuteTemplate("actionCreators", actionCreatorsT, funcs, data); err != nil {
return
}
}
}
return err
}
func (g *Generator) generateReduxActionTypes(jsFile string, api *design.APIDefinition, res *design.ResourceDefinition) (err error) {
funcs := template.FuncMap{"params": params, "toUpper": strings.ToUpper, "resourceName": resourceName, "actionUnderResource": actionUnderResource}
file, err := codegen.SourceFileFor(jsFile)
if err != nil {
return
}
g.genfiles = append(g.genfiles, jsFile)
actions := make(map[string][]*design.ActionDefinition)
res.IterateActions(func(action *design.ActionDefinition) error {
if as, ok := actions[action.Name]; ok {
actions[action.Name] = append(as, action)
} else {
actions[action.Name] = []*design.ActionDefinition{action}
}
return nil
})
keys := []string{}
for n := range actions {
keys = append(keys, n)
}
sort.Strings(keys)
for _, n := range keys {
Actions:
for _, a := range actions[n] {
for _, scheme := range a.Schemes {
if scheme == "ws" {
continue Actions
}
}
data := map[string]interface{}{"Action": a, "ResourceName": actionResourceName(res, a)}
if err = file.ExecuteTemplate("actionTypes", actionTypesT, funcs, data); err != nil {
return
}
}
}
return err
}
func (g *Generator) generateReduxActions(jsFile string, api *design.APIDefinition, res *design.ResourceDefinition) (err error) {
file, err := codegen.SourceFileFor(jsFile)
if err != nil {
return
}
g.genfiles = append(g.genfiles, jsFile)
if res == nil {
return
}
data := map[string]interface{}{
"API": api,
"BaseName": baseName(res),
}
funcs := template.FuncMap{"params": params, "toUpper": strings.ToUpper, "resourceName": resourceName, "actionUnderResource": actionUnderResource}
if err = file.ExecuteTemplate("beginActions", beginActionsT, funcs, data); err != nil {
return
}
actions := make(map[string][]*design.ActionDefinition)
res.IterateActions(func(action *design.ActionDefinition) error {
if as, ok := actions[action.Name]; ok {
actions[action.Name] = append(as, action)
} else {
actions[action.Name] = []*design.ActionDefinition{action}
}
return nil
})
keys := []string{}
for n := range actions {
keys = append(keys, n)
}
sort.Strings(keys)
for _, n := range keys {
Actions:
for _, a := range actions[n] {
for _, scheme := range a.Schemes {
if scheme == "ws" {
continue Actions
}
}
data := map[string]interface{}{
"Action": a,
"API": api,
"ResourceName": actionResourceName(res, a),
}
if err = file.ExecuteTemplate("actions", actionsT, funcs, data); err != nil {
return
}
}
}
return err
}
func resourceName(res *design.ResourceDefinition) string {
name := strings.TrimLeft(res.BasePath, "/")
singular := true
for _, response := range res.Responses {
if response != nil && strings.Contains(response.MediaType, "type=collection") {
singular = false
}
}
if singular {
name = JavaScriptify(inflect.Singularize(name), false, false)
} else {
name = JavaScriptify(inflect.Pluralize(name), false, false)
}
return name
}
func baseName(res *design.ResourceDefinition) string {
return JavaScriptify(inflect.Singularize(strings.TrimLeft(res.BasePath, "/")), false, false)
}
func actionResourceName(res *design.ResourceDefinition, action *design.ActionDefinition) string {
name := strings.TrimLeft(res.BasePath, "/")
singular := true
for _, response := range action.Responses {
if response != nil && strings.Contains(response.MediaType, "type=collection") {
singular = false
}
}
if singular {
name = JavaScriptify(inflect.Singularize(name), false, false)
} else {
name = JavaScriptify(inflect.Pluralize(name), false, false)
}
return name
}
// Cleanup removes all the files generated by this generator during the last invokation of Generate.
func (g *Generator) Cleanup() {
for _, f := range g.genfiles {
os.Remove(f)
}
g.genfiles = nil
}
// Helper for templates to combine action name and resource name
// into a JavaScript safe string for naming redux action types
func actionUnderResource(action string, resource string) string {
return fmt.Sprint(
// Its ok for the action be a reserved word here
strings.ToUpper(JavaScriptify(action, false, true)),
"_",
strings.ToUpper(JavaScriptify(resource, false, false)),
)
}
func params(action *design.ActionDefinition) []string {
if action.QueryParams == nil {
return nil
}
params := make([]string, len(action.QueryParams.Type.ToObject()))
i := 0
for n := range action.QueryParams.Type.ToObject() {
params[i] = n
i++
}
sort.Strings(params)
return params
}
const beginActionsT = `// This module exports redux actions for the {{.API.Name}} API hosted at {{.API.Host}}.
import * as types from './{{.BaseName}}ActionTypes';
`
const beginActionCreatorsT = `// This module exports redux action creators for the {{.API.Name}} API hosted at {{.API.Host}}.
// Redux Thunk middleware or equivalent is required to use these action creators.
// It uses the axios javascript library for making the actual HTTP requests.
import axios from 'axios';
import * as actions from './{{.BaseName}}Actions';
`
const actionCreatorsT = `{{$params := params .Action}}{{$resourceName := .ResourceName}}{{$actionName := .Action.Name}}
// {{$actionName}}{{title $resourceName}} calls the {{.Action.Name}} action of the {{.Action.Parent.Name}} resource.
// url is the request url, the format is:
// {{.Scheme}}://{{.Host}}{{(index .Action.Routes 0).FullPath}}
// Optional handleError and handleSuccess functions can be provided for the promise
// if needed in addition to the redux actions.
// Standard or custom headers can be passed in like this in the options:
// { headers: {'X-My-Custom-Header': 'Header-Value'} }
{{if .Action.Payload}}// data contains the action payload (request body)
{{end}}// The options object will take precedence over default values for timeout, etc.
// This function returns a promise which dispatches an error if the HTTP response is a 4xx or 5xx.
{{if $params}}//
// Query Parameters: {{join $params ", "}} {{if gt (len $params) 1}}are{{else}}is{{end}} expected in params.
{{end}}// Params should be passed in the options object.
export const {{$actionName}}{{title $resourceName}} = (url, options{{if .Action.Payload}}, data{{end}}, handleSuccess, handleError) =>
dispatch => {
dispatch(actions.request{{title $actionName}}{{title $resourceName}}());
return axios({
timeout: {{.Timeout}},
url,
method: '{{toLower (index .Action.Routes 0).Verb}}',
{{if .Action.Payload}} data,
{{end}} responseType: 'json',
...options
})
.then(response => {
dispatch(actions.receive{{title $actionName}}{{title $resourceName}}Success(response.data, response.status));
})
.then(response => {
if (handleSuccess) {
handleSuccess(response);
}
})
.catch(error => {
let rdata;
let rstatus;
if (error.response) {
rdata = error.response.data;
rstatus = error.response.status;
}
dispatch(actions.receive{{title $actionName}}{{title $resourceName}}Error(rdata, rstatus));
throw error;
})
.catch(error => {
if (handleError) {
handleError(error);
}
});
};
`
const actionTypesT = `{{$resourceName := .ResourceName}}{{$actionName := .Action.Name}}export const REQ_{{ actionUnderResource $actionName $resourceName}} = 'REQ_{{actionUnderResource $actionName $resourceName}}';
export const RCV_{{actionUnderResource $actionName $resourceName}}_SUCCESS = 'RCV_{{actionUnderResource $actionName $resourceName}}_SUCCESS';
export const RCV_{{actionUnderResource $actionName $resourceName}}_ERROR = 'RCV_{{actionUnderResource $actionName $resourceName}}_ERROR';
`
const actionsT = `{{$resourceName := .ResourceName}}{{$actionName := .Action.Name}}export const request{{title $actionName}}{{title $resourceName}} = () => ({
type: types.REQ_{{actionUnderResource $actionName $resourceName}}
});
export const receive{{title $actionName}}{{title $resourceName}}Success = (data, status) => ({
type: types.RCV_{{actionUnderResource $actionName $resourceName}}_SUCCESS,
data,
status
});
export const receive{{title $actionName}}{{title $resourceName}}Error = (data, status) => ({
type: types.RCV_{{actionUnderResource $actionName $resourceName}}_ERROR,
data,
status
});
`