From e770b314027dc1258fa6504dde77aad14c8cd7f9 Mon Sep 17 00:00:00 2001 From: Justin Lin Date: Tue, 26 Aug 2025 19:49:37 +1000 Subject: [PATCH] feat: add mapping functions --- cmd/api/main.go | 6 +++--- internal/author/controller.go | 6 +++--- internal/author/mapper.go | 21 +++++++++++++++++++++ internal/author/model.go | 7 +++++++ internal/author/router.go | 2 +- 5 files changed, 35 insertions(+), 7 deletions(-) create mode 100644 internal/author/mapper.go create mode 100644 internal/author/model.go diff --git a/cmd/api/main.go b/cmd/api/main.go index a6f1da0..f56f25e 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -7,7 +7,7 @@ import ( "github.com/gin-gonic/gin" "github.com/jackc/pgx/v5" - user "tutorial.sqlc.dev/app/internal/author" + "tutorial.sqlc.dev/app/internal/author" ) func run() error { @@ -20,8 +20,8 @@ func run() error { defer conn.Close(ctx) r := gin.Default() - userCtl := user.NewController(conn) - user.Register(r, &userCtl) + authorCtl := author.NewController(conn) + author.Register(r, &authorCtl) r.Run(":8000") return nil diff --git a/internal/author/controller.go b/internal/author/controller.go index 9fa29b3..0333f9a 100644 --- a/internal/author/controller.go +++ b/internal/author/controller.go @@ -1,4 +1,4 @@ -package user +package author import ( "strconv" @@ -23,7 +23,7 @@ func (u *Controller) ListAuthors(c *gin.Context) { c.AbortWithError(500, err) return } - c.JSON(200, authors) + c.JSON(200, toAuthorSlice(authors)) } func (u *Controller) GetAuthorByID(c *gin.Context) { @@ -39,5 +39,5 @@ func (u *Controller) GetAuthorByID(c *gin.Context) { return } - c.JSON(200, author) + c.JSON(200, toAuthor(author)) } diff --git a/internal/author/mapper.go b/internal/author/mapper.go new file mode 100644 index 0000000..83c7fc4 --- /dev/null +++ b/internal/author/mapper.go @@ -0,0 +1,21 @@ +package author + +import "tutorial.sqlc.dev/app/internal/author/gen" + +func toAuthor(a gen.Author) Author { + return Author{ + a.ID, a.Name, a.Bio.String, + } +} + +func mapSlice[K any, V any](conv func(K) V) func([]K) []V { + return func(inputs []K) []V { + output := make([]V, len(inputs)) + for i, input := range inputs { + output[i] = conv(input) + } + return output + } +} + +var toAuthorSlice = mapSlice(toAuthor) diff --git a/internal/author/model.go b/internal/author/model.go new file mode 100644 index 0000000..d579ede --- /dev/null +++ b/internal/author/model.go @@ -0,0 +1,7 @@ +package author + +type Author struct { + ID int64 `json:"id"` + Name string `json:"name"` + Bio string `json:"bio"` +} diff --git a/internal/author/router.go b/internal/author/router.go index a5b20b1..a3a66e0 100644 --- a/internal/author/router.go +++ b/internal/author/router.go @@ -1,4 +1,4 @@ -package user +package author import "github.com/gin-gonic/gin"