Skip to content

Commit

Permalink
fix(validation): prettier error in case of swagger file
Browse files Browse the repository at this point in the history
Prettier error outup in case of swagger file/version. Before it returned Atoi parsing error because it was fed an empty string.
  • Loading branch information
alesbrelih committed Jan 22, 2024
1 parent f33c696 commit 08abe67
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
21 changes: 21 additions & 0 deletions openapi/parser/_testdata/negative/version/swagger.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"swagger": "2.0",
"info": {
"title": "Sample API",
"description": "API description in Markdown.",
"version": "1.0.0"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": ["https"],
"paths": {
"/users": {
"get": {
"summary": "Returns a list of users.",
"description": "Optional extended description in Markdown.",
"produces": ["application/json"],
"responses": { "200": { "description": "OK" } }
}
}
}
}
10 changes: 8 additions & 2 deletions openapi/parser/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,17 @@ func (p *parser) parseVersion() (rerr error) {
defer func() {
rerr = p.wrapLocation(p.rootFile, p.rootLoc.Field("openapi"), rerr)
}()
if err := p.version.UnmarshalText([]byte(p.spec.OpenAPI)); err != nil {

version := p.spec.OpenAPI
if version == "" {
version = p.spec.Swagger
}

if err := p.version.UnmarshalText([]byte(version)); err != nil {
return errors.Wrap(err, "invalid version")
}
if p.version.Major != 3 || p.version.Minor > 1 {
return errors.Errorf("unsupported version: %s", p.spec.OpenAPI)
return errors.Errorf("unsupported version: %s", version)
}
return nil
}
Expand Down
2 changes: 2 additions & 0 deletions spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ type Spec struct {
// REQUIRED. This string MUST be the version number of the OpenAPI Specification
// that the OpenAPI document uses.
OpenAPI string `json:"openapi" yaml:"openapi"`
// Added just to detect v2 openAPI specifications and to pretty print version error.
Swagger string `json:"swagger,omitempty" yaml:"swagger,omitempty"`
// REQUIRED. Provides metadata about the API.
//
// The metadata MAY be used by tooling as required.
Expand Down
13 changes: 13 additions & 0 deletions spec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,16 @@ func TestComponents_Init(t *testing.T) {
a.NotNil(f.Interface())
}
}

func TestSwaggerExtraction(t *testing.T) {
a := require.New(t)

{
var (
input = `{"swagger": "2.0.0"}`
s ogen.Spec
)
a.NoError(yaml.Unmarshal([]byte(input), &s))
a.Equal("2.0.0", s.Swagger)
}
}

0 comments on commit 08abe67

Please sign in to comment.