dorfylegends/analyze/df/generate_frontend.go

78 lines
1.4 KiB
Go
Raw Normal View History

2022-04-16 21:34:19 +03:00
package df
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"text/template"
"github.com/iancoleman/strcase"
)
var frontendTemplate = template.Must(template.New("").Parse(`// Code generated by legendsbrowser; DO NOT EDIT.
{{- range $name, $obj := $.Objects }}
export interface {{ $obj.Name }} {
{{- range $fname, $field := $obj.Fields }}
{{- if not (and (eq $fname "type") (not (not $obj.SubTypes))) }}
{{ $field.JsonTypeLine }};
{{- end }}
{{- end }}
{{- if not (not $obj.SubTypes) }}
Details: any;
{{- end }}
}
{{- end }}
`))
func generateFrontendCode(objects *Metadata) error {
file, _ := json.MarshalIndent(objects, "", " ")
_ = ioutil.WriteFile("model.json", file, 0644)
f, err := os.Create("../frontend/src/app/types.ts")
if err != nil {
return err
}
defer f.Close()
var buf bytes.Buffer
err = frontendTemplate.Execute(&buf, struct {
Objects *Metadata
Modes []bool
}{
Objects: objects,
Modes: []bool{false, true},
})
if err != nil {
return err
}
_, err = f.Write(buf.Bytes())
return err
}
func (f Field) JsonTypeLine() string {
m := ""
if f.Multiple {
m = "[]"
}
t := f.Type
if f.Type == "int" {
t = "number"
}
2022-04-16 23:12:23 +03:00
if f.Type == "bool" {
t = "boolean"
}
2022-04-16 21:34:19 +03:00
if f.Type == "array" {
t = *f.ElementType + "[]"
}
if f.Type == "map" {
t = "{ [key:number]:" + *f.ElementType + "; }"
}
if f.Type == "object" {
t = *f.ElementType
}
return fmt.Sprintf("%s: %s%s", strcase.ToLowerCamel(f.Name), t, m)
}