From ed5b92c1ef61e1f766aa195603cf2fe09602834b Mon Sep 17 00:00:00 2001 From: sdghchj Date: Tue, 6 Feb 2024 10:11:29 +0800 Subject: [PATCH] support primitive type with format in response Signed-off-by: sdghchj --- operation.go | 10 +++++++++- operation_test.go | 27 +++++++++++++++++++++++++++ schema.go | 6 ++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/operation.go b/operation.go index 169510ffc..d331169eb 100644 --- a/operation.go +++ b/operation.go @@ -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 } } diff --git a/operation_test.go b/operation_test.go index fb43a446e..f3f1bc78b 100644 --- a/operation_test.go +++ b/operation_test.go @@ -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() diff --git a/schema.go b/schema.go index b3a5b38c1..e2ffcff7b 100644 --- a/schema.go +++ b/schema.go @@ -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) {