From ae7a76d42108840fbc890644783b480a278ef1ff Mon Sep 17 00:00:00 2001 From: Matthias Schneider Date: Fri, 25 Feb 2022 09:56:20 +0100 Subject: [PATCH] #1140 added SchemaExample() to set the example to schema --- operation.go | 18 ++++++++++++++++++ operation_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/operation.go b/operation.go index 16d748891..5d35963cc 100644 --- a/operation.go +++ b/operation.go @@ -360,6 +360,7 @@ const ( defaultTag = "default" enumsTag = "enums" exampleTag = "example" + schemaExampleTag = "schemaExample" formatTag = "format" validateTag = "validate" minimumTag = "minimum" @@ -393,6 +394,8 @@ var regexAttributes = map[string]*regexp.Regexp{ collectionFormatTag: regexp.MustCompile(`(?i)\s+collectionFormat\(.*\)`), // example(0) exampleTag: regexp.MustCompile(`(?i)\s+example\(.*\)`), + // schemaExample(0) + schemaExampleTag: regexp.MustCompile(`(?i)\s+schemaExample\(.*\)`), } func (operation *Operation) parseAndExtractionParamAttribute(commentLine, objectType, schemaType string, param *spec.Parameter) error { @@ -415,6 +418,8 @@ func (operation *Operation) parseAndExtractionParamAttribute(commentLine, object param.Format = attr case exampleTag: err = setExample(param, schemaType, attr) + case schemaExampleTag: + err = setSchemaExample(param, schemaType, attr) case extensionsTag: _ = setExtensionParam(param, attr) case collectionFormatTag: @@ -530,6 +535,19 @@ func setDefault(param *spec.Parameter, schemaType string, value string) error { return nil } +func setSchemaExample(param *spec.Parameter, schemaType string, value string) error { + val, err := defineType(schemaType, value) + if err != nil { + return nil // Don't set a example value if it's not valid + } + // skip schema + if param.Schema == nil { + return nil + } + param.Schema.Example = val + return nil +} + func setExample(param *spec.Parameter, schemaType string, value string) error { val, err := defineType(schemaType, value) if err != nil { diff --git a/operation_test.go b/operation_test.go index 8eb89b5f0..dd549c7c9 100644 --- a/operation_test.go +++ b/operation_test.go @@ -1882,6 +1882,30 @@ func TestParseParamCommentByExampleUnsupportedType(t *testing.T) { assert.Equal(t, param.Example, float64(10)) } +func TestParseParamCommentBySchemaExampleString(t *testing.T) { + t.Parallel() + + comment := `@Param some_id body string true "Some ID" SchemaExample(True feelings)` + operation := NewOperation(nil) + err := operation.ParseComment(comment, nil) + + assert.NoError(t, err) + b, _ := json.MarshalIndent(operation.Parameters, "", " ") + expected := `[ + { + "description": "Some ID", + "name": "some_id", + "in": "body", + "required": true, + "schema": { + "type": "string", + "example": "True feelings" + } + } +]` + assert.Equal(t, expected, string(b)) +} + func TestParseParamArrayWithEnums(t *testing.T) { t.Parallel()