Skip to content

Commit

Permalink
refactor(hz): client query enum (#1064)
Browse files Browse the repository at this point in the history
#### What type of PR is this?
<!--
Add one of the following kinds:

build: Changes that affect the build system or external dependencies
(example scopes: gulp, broccoli, npm)
ci: Changes to our CI configuration files and scripts (example scopes:
Travis, Circle, BrowserStack, SauceLabs)
docs: Documentation only changes
feat: A new feature
optimize: A new optimization
fix: A bug fix
perf: A code change that improves performance
refactor: A code change that neither fixes a bug nor adds a feature
style: Changes that do not affect the meaning of the code (white space,
formatting, missing semi-colons, etc)
test: Adding missing tests or correcting existing tests
chore: Changes to the build process or auxiliary tools and libraries
such as documentation generation
-->
refactor
#### Check the PR title.
<!--
The description of the title will be attached in Release Notes, 
so please describe it from user-oriented, what this PR does / why we
need it.
Please check your PR title with the below requirements:
-->
- [x] This PR title match the format: \<type\>(optional scope):
\<description\>
- [x] The description of this PR title is user-oriented and clear enough
for others to understand.
- [x] Attach the PR updating the user documentation if the current PR
requires user awareness at the usage level. [User docs
repo](https://github.com/cloudwego/cloudwego.github.io)


#### (Optional) Translate the PR title into Chinese.
重构 client query 对于 enum 传递的配置形式

#### (Optional) More detailed description for this PR(en: English/zh:
Chinese).
<!--
Provide more detailed info for review(e.g., it's recommended to provide
perf data if this is a perf type PR).
-->
en: Refactoring the client query's configuration form for enum
zh(optional): 重构 client query 对于 enum 传递的配置形式

#### (Optional) Which issue(s) this PR fixes:
<!--
Automatically closes linked issue when PR is merged.
Eg: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
-->

#### (Optional) The PR that updates user documentation:
<!--
If the current PR requires user awareness at the usage level, please
submit a PR to update user docs. [User docs
repo](https://github.com/cloudwego/cloudwego.github.io)
-->
  • Loading branch information
FGYFFFF authored Apr 18, 2024
2 parents 3b3296c + 3bc1be6 commit 0285a34
Show file tree
Hide file tree
Showing 7 changed files with 26 additions and 18 deletions.
2 changes: 2 additions & 0 deletions cmd/hz/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ func Init() *cli.App {
enableExtendsFlag := cli.BoolFlag{Name: "enable_extends", Usage: "Parse 'extends' for thrift IDL", Destination: &globalArgs.EnableExtends}

jsonEnumStrFlag := cli.BoolFlag{Name: "json_enumstr", Usage: "Use string instead of num for json enums when idl is thrift.", Destination: &globalArgs.JSONEnumStr}
queryEnumIntFlag := cli.BoolFlag{Name: "query_enumint", Usage: "Use num instead of string for query enum parameter.", Destination: &globalArgs.QueryEnumAsInt}
unsetOmitemptyFlag := cli.BoolFlag{Name: "unset_omitempty", Usage: "Remove 'omitempty' tag for generated struct.", Destination: &globalArgs.UnsetOmitempty}
protoCamelJSONTag := cli.BoolFlag{Name: "pb_camel_json_tag", Usage: "Convert Name style for json tag to camel(Only works protobuf).", Destination: &globalArgs.ProtobufCamelJSONTag}
snakeNameFlag := cli.BoolFlag{Name: "snake_tag", Usage: "Use snake_case style naming for tags. (Only works for 'form', 'query', 'json')", Destination: &globalArgs.SnakeName}
Expand Down Expand Up @@ -316,6 +317,7 @@ func Init() *cli.App {
&enableExtendsFlag,

&jsonEnumStrFlag,
&queryEnumIntFlag,
&unsetOmitemptyFlag,
&protoCamelJSONTag,
&snakeNameFlag,
Expand Down
1 change: 1 addition & 0 deletions cmd/hz/config/argument.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ type Argument struct {
NeedGoMod bool

JSONEnumStr bool
QueryEnumAsInt bool
UnsetOmitempty bool
ProtobufCamelJSONTag bool
ProtocOptions []string // options to pass through to protoc
Expand Down
6 changes: 6 additions & 0 deletions cmd/hz/generator/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ type ClientMethod struct {
FormFileCode string
}

type ClientConfig struct {
QueryEnumAsInt bool
}

type ClientFile struct {
Config ClientConfig
FilePath string
PackageName string
ServiceName string
Expand Down Expand Up @@ -64,6 +69,7 @@ func (pkgGen *HttpPackageGenerator) genClient(pkg *HttpPackage, clientDir string
ServiceName: util.ToCamelCase(s.Name),
ClientMethods: s.ClientMethods,
BaseDomain: baseDomain,
Config: ClientConfig{QueryEnumAsInt: pkgGen.QueryEnumAsInt},
}
if !isExist {
err := pkgGen.TemplateGenerator.Generate(client, hertzClientTplName, hertzClientPath, false)
Expand Down
1 change: 1 addition & 0 deletions cmd/hz/generator/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ type HttpPackageGenerator struct {
IdlClientDir string // client dir for "client" command
ForceClientDir string // client dir without namespace for "client" command
BaseDomain string // request domain for "client" command
QueryEnumAsInt bool // client code use number for query parameter
ServiceGenDir string

NeedModel bool
Expand Down
32 changes: 14 additions & 18 deletions cmd/hz/generator/package_tpl.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,6 @@ type Option struct {
type Options struct {
hostUrl string
enumAsInt bool
doer client.Doer
header http.Header
requestBodyBind bindRequestBodyFunc
Expand Down Expand Up @@ -376,13 +375,6 @@ func WithResponseResultDecider(decider ResponseResultDecider) Option {
}}
}
// WithQueryEnumAsInt is used to set enum as int for query parameters
func WithQueryEnumAsInt(enable bool) Option {
return Option{func(op *Options) {
op.enumAsInt = enable
}}
}
func withHostUrl(HostUrl string) Option {
return Option{func(op *Options) {
op.hostUrl = HostUrl
Expand All @@ -392,7 +384,6 @@ func withHostUrl(HostUrl string) Option {
// underlying client
type cli struct {
hostUrl string
enumAsInt bool
doer client.Doer
header http.Header
bindRequestBody bindRequestBodyFunc
Expand Down Expand Up @@ -428,7 +419,6 @@ func newClient(opts *Options) (*cli, error) {
c := &cli{
hostUrl: opts.hostUrl,
enumAsInt: opts.enumAsInt,
doer: opts.doer,
header: opts.header,
bindRequestBody: opts.requestBodyBind,
Expand Down Expand Up @@ -505,12 +495,13 @@ func (c *cli) execute(req *request) (*response, error) {
// r get request
func (c *cli) r() *request {
return &request{
queryParam: url.Values{},
header: http.Header{},
pathParam: map[string]string{},
formParam: map[string]string{},
fileParam: map[string]string{},
client: c,
queryParam: url.Values{},
header: http.Header{},
pathParam: map[string]string{},
formParam: map[string]string{},
fileParam: map[string]string{},
client: c,
queryEnumAsInt: {{.Config.QueryEnumAsInt}},
}
}
Expand Down Expand Up @@ -556,6 +547,7 @@ type request struct {
client *cli
url string
method string
queryEnumAsInt bool
queryParam url.Values
header http.Header
pathParam map[string]string
Expand Down Expand Up @@ -601,10 +593,14 @@ func (r *request) setQueryParam(param string, value interface{}) *request {
switch v.Kind() {
case reflect.Slice, reflect.Array:
for index := 0; index < v.Len(); index++ {
r.queryParam.Add(param, fmt.Sprint(v.Index(index).Interface()))
if r.queryEnumAsInt && (v.Index(index).Kind() == reflect.Int32 || v.Index(index).Kind() == reflect.Int64) {
r.queryParam.Add(param, fmt.Sprintf("%d", v.Index(index).Interface()))
} else {
r.queryParam.Add(param, fmt.Sprint(v.Index(index).Interface()))
}
}
case reflect.Int32, reflect.Int64:
if r.client.enumAsInt {
if r.queryEnumAsInt {
r.queryParam.Add(param, fmt.Sprintf("%d", v.Interface()))
} else {
r.queryParam.Add(param, fmt.Sprint(v))
Expand Down
1 change: 1 addition & 0 deletions cmd/hz/protobuf/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,7 @@ func (plugin *Plugin) genHttpPackage(ast *descriptorpb.FileDescriptorProto, deps
IdlClientDir: plugin.IdlClientDir,
ForceClientDir: args.ForceClientDir,
BaseDomain: args.BaseDomain,
QueryEnumAsInt: args.QueryEnumAsInt,
SnakeStyleMiddleware: args.SnakeStyleMiddleware,
}

Expand Down
1 change: 1 addition & 0 deletions cmd/hz/thrift/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ func (plugin *Plugin) Run() int {
IdlClientDir: util.SubDir(modelDir, pkgInfo.Package),
ForceClientDir: args.ForceClientDir,
BaseDomain: args.BaseDomain,
QueryEnumAsInt: args.QueryEnumAsInt,
SnakeStyleMiddleware: args.SnakeStyleMiddleware,
}
if args.ModelBackend != "" {
Expand Down

0 comments on commit 0285a34

Please sign in to comment.