Last active
September 22, 2023 16:26
-
-
Save xrstf/cdfb3bfae8cc40aae32ea6b1b3270225 to your computer and use it in GitHub Desktop.
Resolve Refs in OpenAPI3 spec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module testmodule | |
go 1.21.0 | |
require github.com/getkin/kin-openapi v0.120.0 | |
require ( | |
github.com/go-openapi/jsonpointer v0.19.6 // indirect | |
github.com/go-openapi/swag v0.22.4 // indirect | |
github.com/invopop/yaml v0.2.0 // indirect | |
github.com/josharian/intern v1.0.0 // indirect | |
github.com/mailru/easyjson v0.7.7 // indirect | |
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect | |
github.com/perimeterx/marshmallow v1.1.5 // indirect | |
gopkg.in/yaml.v3 v3.0.1 // indirect | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"github.com/getkin/kin-openapi/openapi3" | |
) | |
func main() { | |
contents, err := os.ReadFile("foo.json") | |
if err != nil { | |
log.Fatal(err) | |
} | |
doc, err := openapi3.NewLoader().LoadFromData(contents) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// kin already resolves internal refs by default, | |
// however when marshalling back to JSON it prefers | |
// to output the ref if it's set; to prevent this, | |
// we walk through the document and remove all refs; | |
// NB: This might result in an inifite loop if your | |
// spec had circular references. | |
derefSchemas(doc.Components.Schemas) | |
j, err := doc.MarshalJSON() | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(string(j)) | |
} | |
func derefSchemas(schemas openapi3.Schemas) { | |
for _, schemaRef := range schemas { | |
derefSchemaRef(schemaRef) | |
} | |
} | |
func derefSchemaRefs(schemaRefs openapi3.SchemaRefs) { | |
for _, schemaRef := range schemaRefs { | |
derefSchemaRef(schemaRef) | |
} | |
} | |
func derefSchemaRef(schemaRef *openapi3.SchemaRef) { | |
if schemaRef == nil { | |
return | |
} | |
schemaRef.Ref = "" | |
val := schemaRef.Value | |
derefSchemaRefs(val.OneOf) | |
derefSchemaRefs(val.OneOf) | |
derefSchemaRefs(val.AllOf) | |
derefSchemaRef(val.Not) | |
derefSchemaRef(val.Items) | |
derefSchemas(val.Properties) | |
derefSchemaRef(val.AdditionalProperties.Schema) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment