Skip to content

Commit 1124314

Browse files
committed
fix: don't generate duplicate query decoder functions
1 parent b446b64 commit 1124314

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

cmd/happy/main.go

+10-3
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,9 @@ See https://github.com/thnxdev/happy for more information.
8787
didWork = true
8888

8989
gctx := &genContext{
90-
Writer: codewriter.New(pkg.Name),
91-
pkg: pkg,
90+
Writer: codewriter.New(pkg.Name),
91+
pkg: pkg,
92+
haveDecoder: map[string]bool{},
9293
}
9394
gctx.Import("net/http", "io", "encoding/json", "strconv")
9495
for _, svcEndpoints := range endpoints {
@@ -352,6 +353,10 @@ func genQueryDecoderFunc(gctx *genContext, paramType types.Type) (name string, e
352353
gctx.Import("net/url")
353354
_, typeRef := gctx.TypeRef(paramType)
354355
name = "decode" + ucFirst(strings.ReplaceAll(typeRef, ".", ""))
356+
if gctx.haveDecoder[typeRef] {
357+
return name, nil
358+
}
359+
gctx.haveDecoder[typeRef] = true
355360
w := gctx.Trailer()
356361
w.L("func %s(p url.Values, out *%s) (err error) {", name, typeRef)
357362
w = w.Push()
@@ -374,6 +379,7 @@ func genQueryDecoderFunc(gctx *genContext, paramType types.Type) (name string, e
374379
w.L("out.%s = new(%s)", field.Name(), fieldType)
375380
strctRef = "*" + strctRef
376381
}
382+
w.Import("fmt")
377383
switch fieldType.String() {
378384
case "time.Duration":
379385
gctx.Import("time")
@@ -423,6 +429,7 @@ func lcFirst(s string) string {
423429
type genContext struct {
424430
pkg *packages.Package
425431
*codewriter.Writer
432+
haveDecoder map[string]bool
426433
}
427434

428435
func (g *genContext) Pos(pos token.Pos) token.Position {
@@ -536,7 +543,7 @@ func genEndpoint(gctx *genContext, w *codewriter.Writer, ep endpoint) error {
536543
return fmt.Errorf("%s: %w", pos, err)
537544
}
538545
w.L("if err := %s(r.URL.Query(), &param%d); err != nil {", decoderFn, i)
539-
w.L(` http.Error(w, fmt.Sprintf("Failed to decode query parameters: %%s", err), http.StatusBadRequest)`)
546+
w.L(` http.Error(w, err.Error(), http.StatusBadRequest)`)
540547
w.L(" return")
541548
w.L("}")
542549
} else {

0 commit comments

Comments
 (0)