Skip to content

Commit

Permalink
[release-0.2] feat(*): add a Optional field to the Parameter struct (#…
Browse files Browse the repository at this point in the history
…348)

* fix(*): handle the situation when the parameter is nil

* feat(*): add a Optional field to the Parameter struct

* fix lint

Co-authored-by: iawia002 <[email protected]>
  • Loading branch information
caicloud-bot and iawia002 authored Jul 20, 2020
1 parent af0c9cf commit 6aa8292
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 6 deletions.
21 changes: 21 additions & 0 deletions definition/definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,27 @@ type Parameter struct {
Operators []Operator
// Description describes the parameter.
Description string
// Optional used to set whether this parameter is optional or not, we take the File parameter as an example,
// in current usage, if the value of parameter is empty, nirvana will return an error directly:
// {
// "reason": "Nirvana:Service:RequiredField",
// "message": "required field file in File but got empty",
// "data": {
// "field": "file",
// "source": "File"
// }
// }
//
// if you set the `Optional` to true, then nirvana won't interrupt the request, you can handle
// the situation where the parameter may be nil yourself, eg:
//
// func Upload(ctx context.Context, file multipart.File) (string, error) {
// if file == nil {
// // do something
// }
// // do something else
// }
Optional bool
}

// Result describes how to handle a result from function results.
Expand Down
86 changes: 86 additions & 0 deletions examples/getting-started/file/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
Copyright 2020 Caicloud Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"context"
"io/ioutil"
"mime/multipart"

"github.com/caicloud/nirvana/config"
"github.com/caicloud/nirvana/definition"
"github.com/caicloud/nirvana/log"
)

func Upload(ctx context.Context, file multipart.File) (string, error) {
if file == nil {
return "no content", nil
}
f, err := ioutil.ReadAll(file)
if err != nil {
return "", nil
}
return string(f), nil
}

func main() {
descriptors := []definition.Descriptor{
{
Path: "/required",
Description: "Upload API",
Definitions: []definition.Definition{
{
Method: definition.Create,
Function: Upload,
Consumes: []string{definition.MIMEAll},
Produces: []string{definition.MIMEAll},
Parameters: []definition.Parameter{
{
Source: definition.File,
Name: "file",
},
},
Results: definition.DataErrorResults(""),
},
},
},
{
Path: "/optional",
Description: "Upload API",
Definitions: []definition.Definition{
{
Method: definition.Create,
Function: Upload,
Consumes: []string{definition.MIMEAll},
Produces: []string{definition.MIMEAll},
Parameters: []definition.Parameter{
{
Source: definition.File,
Name: "file",
Optional: true,
},
},
Results: definition.DataErrorResults(""),
},
},
},
}
cmd := config.NewDefaultNirvanaCommand()
if err := cmd.Execute(descriptors...); err != nil {
log.Fatal(err)
}
}
2 changes: 1 addition & 1 deletion hack/verify_boilerplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def get_regexs():
# Search for "YEAR" which exists in the boilerplate, but shouldn't in the real thing
regexs["year"] = re.compile('YEAR')
# dates can be 2017 or 2018, company holder names can be anything
regexs["date"] = re.compile('(2017|2018)')
regexs["date"] = re.compile('(2017|2018|2019|2020)')
# strip // +build \n\n build constraints
regexs["go_build_constraints"] = re.compile(r"^(// \+build.*\n)+\n", re.MULTILINE)
# strip #!.* from shell/python scripts
Expand Down
15 changes: 12 additions & 3 deletions service/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ func (i *inspector) generateParameters(funcName string, typ reflect.Type, ps []d
defaultValue: p.Default,
generator: generator,
operators: p.Operators,
optional: p.Optional,
}
if len(p.Operators) <= 0 {
param.targetType = typ.In(index)
Expand Down Expand Up @@ -379,6 +380,7 @@ type parameter struct {
defaultValue interface{}
generator ParameterGenerator
operators []definition.Operator
optional bool
}

type result struct {
Expand Down Expand Up @@ -447,9 +449,12 @@ func (e *executor) Execute(ctx context.Context) (err error) {
return writeError(ctx, e.errorProducers, err)
}
}
if result == nil {

if result == nil && !p.optional {
return writeError(ctx, e.errorProducers, requiredField.Error(p.name, p.generator.Source()))
} else if closer, ok := result.(io.Closer); ok {
}

if closer, ok := result.(io.Closer); ok {
defer func() {
if e := closer.Close(); e != nil && err == nil {
// Need to print error here.
Expand All @@ -458,7 +463,11 @@ func (e *executor) Execute(ctx context.Context) (err error) {
}()
}

paramValues = append(paramValues, reflect.ValueOf(result))
if result == nil {
paramValues = append(paramValues, reflect.New(p.targetType).Elem())
} else {
paramValues = append(paramValues, reflect.ValueOf(result))
}
}
resultValues := e.function.Call(paramValues)
for _, r := range e.results {
Expand Down
3 changes: 3 additions & 0 deletions utils/api/definitions.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ type Parameter struct {
Type TypeName
// Default is encoded default value.
Default []byte
// Optional used to set whether this parameter is optional or not.
Optional bool
}

// Result describes a function result.
Expand Down Expand Up @@ -114,6 +116,7 @@ func NewDefinition(tc *TypeContainer, d *definition.Definition) (*Definition, er
Name: p.Name,
Description: p.Description,
Type: functionType.In[i].Type,
Optional: p.Optional,
}
if p.Default != nil {
data, err := encode(p.Default)
Expand Down
5 changes: 3 additions & 2 deletions utils/generators/swagger/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,10 +444,11 @@ func (g *Generator) generateParameter(param *api.Parameter) []spec.Parameter {
Description: g.escapeNewline(param.Description),
Schema: schema,
In: source,
Required: !param.Optional,
},
}
if len(param.Default) <= 0 {
parameter.Required = true
if len(param.Default) > 0 {
parameter.Required = false
}
if parameter.In != "body" {
// Only body parameter can hold a schema. Other parameters uses type
Expand Down

0 comments on commit 6aa8292

Please sign in to comment.