Skip to content

Instantly share code, notes, and snippets.

@owulveryck
Created June 15, 2021 13:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owulveryck/4bd452cc3692d7016a54131ec89fa09a to your computer and use it in GitHub Desktop.
Save owulveryck/4bd452cc3692d7016a54131ec89fa09a to your computer and use it in GitHub Desktop.
CUE -> OpenAPI generation
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"cuelang.org/go/cue"
"cuelang.org/go/cue/load"
"cuelang.org/go/encoding/openapi"
)
func generateOpenAPI(defFile string, config *load.Config) ([]byte, error) {
buildInstances := load.Instances([]string{defFile}, config)
insts := cue.Build(buildInstances)
b, err := openapi.Gen(insts[0], nil)
if err != nil {
return nil, err
}
var out bytes.Buffer
err = json.Indent(&out, b, "", " ")
if err != nil {
return nil, err
}
return out.Bytes(), nil
}
func ExampleGenerateOpenAPI() {
src := bytes.NewBufferString(`#Identity: {
// first name of the person
first: =~ "[A-Z].*"
// Last name of the person
Last: =~ "[A-Z].*"
// Age of the person
Age?: number & < 130
}
`)
b, err := generateOpenAPI("-", &load.Config{
Stdin: src,
})
if err != nil {
log.Fatal(err)
}
// This contains the OpenAPI.json definition
fmt.Println(string(b))
// output:
// {
// "openapi": "3.0.0",
// "info": {
// "title": "Generated by cue.",
// "version": "no version"
// },
// "paths": {},
// "components": {
// "schemas": {
// "Identity": {
// "type": "object",
// "required": [
// "first",
// "Last"
// ],
// "properties": {
// "first": {
// "description": "first name of the person",
// "type": "string",
// "pattern": "[A-Z].*"
// },
// "Last": {
// "description": "Last name of the person",
// "type": "string",
// "pattern": "[A-Z].*"
// },
// "Age": {
// "description": "Age of the person",
// "type": "number",
// "maximum": 130,
// "exclusiveMaximum": true
// }
// }
// }
// }
// }
// }
}
@khansgithub
Copy link

Was struggling to figure out how to convert cue to openapi, thanks for this great example :D !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment