Skip to content

Commit

Permalink
support primitive type with format in response
Browse files Browse the repository at this point in the history
Signed-off-by: sdghchj <[email protected]>
  • Loading branch information
sdghchj committed Feb 6, 2024
1 parent 98ed434 commit ed5b92c
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
10 changes: 9 additions & 1 deletion operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -978,7 +978,15 @@ func (operation *Operation) parseAPIObjectSchema(commentLine, schemaType, refTyp

return spec.ArrayProperty(schema), nil
default:
return PrimitiveSchema(schemaType), nil
schema := PrimitiveSchema(schemaType)
if refType != schemaType {
//refer to https://swagger.io/specification/v2/#dataTypeFormat
if !validPrimitiveFormat[schemaType][refType] {
return nil, fmt.Errorf("invalid format %s of type %s", refType, schemaType)
}
schema.Format = refType
}
return schema, nil
}
}

Expand Down
27 changes: 27 additions & 0 deletions operation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,33 @@ func TestOperation_ParseResponseWithDefault(t *testing.T) {
assert.Equal(t, "A response", operation.Responses.StatusCodeResponses[200].Description)
}

func TestParseResponsePrimitiveTypeWithFormat(t *testing.T) {
t.Parallel()

comment := `@Success 200 {integer} int16 "response with format"`
operation := NewOperation(nil)
err := operation.ParseComment(comment, nil)
assert.Error(t, err)

comment = `@Success 200 {integer} int32 "response with format"`
operation = NewOperation(nil)
err = operation.ParseComment(comment, nil)
assert.NoError(t, err)
b, _ := json.MarshalIndent(operation, "", " ")
expected := `{
"responses": {
"200": {
"description": "response with format",
"schema": {
"type": "integer",
"format": "int32"
}
}
}
}`
assert.Equal(t, expected, string(b))
}

func TestParseResponseSuccessCommentWithEmptyResponse(t *testing.T) {
t.Parallel()

Expand Down
6 changes: 6 additions & 0 deletions schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ const (
IgnoreNameOverridePrefix = '$'
)

var validPrimitiveFormat = map[string]map[string]bool{
INTEGER: {"int32": true, "int64": true},
NUMBER: {"float": true, "double": true},
STRING: {"byte": true, "binary": true, "date": true, "date-time": true, "password": true},
}

// CheckSchemaType checks if typeName is not a name of primitive type.
func CheckSchemaType(typeName string) error {
if !IsPrimitiveType(typeName) {
Expand Down

0 comments on commit ed5b92c

Please sign in to comment.