Skip to content

Commit

Permalink
fix: some fixes for JS template helpers
Browse files Browse the repository at this point in the history
- Exclude template.js from being inserted into the output.
- Add the template context as a global variable to simplify things.
- Ensure that typeName() doesn't panic if given invalid values.
  • Loading branch information
alecthomas committed Dec 8, 2023
1 parent 7012f1a commit ec8a398
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions cmd/ftl/cmd_schema_generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ import (
"time"

"connectrpc.com/connect"
"github.com/TBD54566975/scaffolder"
"github.com/alecthomas/repr"
"github.com/dop251/goja"
"github.com/iancoleman/strcase"
"github.com/radovskyb/watcher"
"golang.org/x/exp/maps"
"golang.org/x/sync/errgroup"

"github.com/TBD54566975/scaffolder"

"github.com/TBD54566975/ftl/backend/common/log"
"github.com/TBD54566975/ftl/backend/common/slices"
"github.com/TBD54566975/ftl/backend/schema"
Expand Down Expand Up @@ -121,11 +122,11 @@ func (s *schemaGenerateCmd) regenerateModules(logger *log.Logger, modules []*sch
}

for _, module := range modules {
funcs, _, err := s.createJSVM(logger)
funcs, _, err := s.createJSVM(logger, module)
if err != nil {
return fmt.Errorf("failed to create JS VM: %w", err)
}
if err := scaffolder.Scaffold(s.Template, s.Dest, module, scaffolder.Functions(funcs)); err != nil {
if err := scaffolder.Scaffold(s.Template, s.Dest, module, scaffolder.Functions(funcs), scaffolder.Exclude("^template.js$")); err != nil {
return err
}
}
Expand All @@ -134,12 +135,15 @@ func (s *schemaGenerateCmd) regenerateModules(logger *log.Logger, modules []*sch
}

// Create JS VM and populate it with functions that can be used in templates.
func (s *schemaGenerateCmd) createJSVM(logger *log.Logger) (funcs template.FuncMap, vm *goja.Runtime, err error) {
func (s *schemaGenerateCmd) createJSVM(logger *log.Logger, module *schema.Module) (funcs template.FuncMap, vm *goja.Runtime, err error) {
vm = goja.New()
vm.SetFieldNameMapper(goja.UncapFieldNameMapper())
if err := initConsole(vm, logger); err != nil {
return nil, nil, err
}
if err := vm.Set("context", module); err != nil {
return nil, nil, err
}
if err := vm.Set("repr", repr.String); err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -170,8 +174,15 @@ func (s *schemaGenerateCmd) createJSVM(logger *log.Logger) (funcs template.FuncM
if err := vm.Set("title", strings.Title); err != nil {
return nil, nil, err
}
if err := vm.Set("typename", func(v any) string {
return reflect.Indirect(reflect.ValueOf(v)).Type().Name()
if err := vm.Set("typeName", func(v any) string {
if v == nil {
return "null"
}
rv := reflect.ValueOf(v)
if rv == (reflect.Value{}) {
return "<nil>"
}
return reflect.Indirect(rv).Type().Name()
}); err != nil {
return nil, nil, err
}
Expand Down

0 comments on commit ec8a398

Please sign in to comment.