api/export.go

39 lines
1 KiB
Go
Raw Permalink Normal View History

// SPDX-License-Identifier: EUPL-1.2
package api
import (
core "dappco.re/go/core"
"gopkg.in/yaml.v3"
)
// ExportSpec generates the OpenAPI spec and writes it to a core.Fs path.
// Format must be "json" or "yaml".
func ExportSpec(path, format string, builder *SpecBuilder, groups []RouteGroup) core.Result {
r := builder.Build(groups)
if !r.OK {
return r
}
data := r.Value.([]byte)
switch format {
case "json":
return (&core.Fs{}).NewUnrestricted().Write(path, string(data))
case "yaml":
var obj any
if ur := core.JSONUnmarshal(data, &obj); !ur.OK {
return core.Result{Value: core.E("ExportSpec", "unmarshal spec", nil), OK: false}
}
b := core.NewBuilder()
enc := yaml.NewEncoder(b)
enc.SetIndent(2)
if err := enc.Encode(obj); err != nil {
return core.Result{Value: core.E("ExportSpec", "encode yaml", err), OK: false}
}
enc.Close()
return (&core.Fs{}).NewUnrestricted().Write(path, b.String())
default:
return core.Result{Value: core.E("ExportSpec", core.Concat("unsupported format: ", format), nil), OK: false}
}
}