feat: add getAuthorByID

This commit is contained in:
Justin Lin
2025-08-26 19:34:42 +10:00
parent d963362711
commit 0dc1d411f4
2 changed files with 23 additions and 5 deletions

View File

@@ -1,7 +1,7 @@
package user package user
import ( import (
"context" "strconv"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"tutorial.sqlc.dev/app/internal/author/gen" "tutorial.sqlc.dev/app/internal/author/gen"
@@ -17,10 +17,27 @@ func NewController(conn gen.DBTX) Controller {
} }
} }
func (u *Controller) ListAuthors(ctx *gin.Context) { func (u *Controller) ListAuthors(c *gin.Context) {
authors, err := u.queries.ListAuthors(context.Background()) authors, err := u.queries.ListAuthors(c.Request.Context())
if err != nil { if err != nil {
ctx.AbortWithError(500, err) c.AbortWithError(500, err)
return
} }
ctx.JSON(200, authors) c.JSON(200, authors)
}
func (u *Controller) GetAuthorByID(c *gin.Context) {
idStr := c.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil {
c.AbortWithError(400, err)
return
}
author, err := u.queries.GetAuthor(c.Request.Context(), int64(id))
if err != nil {
c.JSON(400, gin.H{"message": "Author not found"})
return
}
c.JSON(200, author)
} }

View File

@@ -5,4 +5,5 @@ import "github.com/gin-gonic/gin"
func Register(r gin.IRouter, ctl *Controller) { func Register(r gin.IRouter, ctl *Controller) {
g := r.Group("/authors") g := r.Group("/authors")
g.GET("", ctl.ListAuthors) g.GET("", ctl.ListAuthors)
g.GET("/:id", ctl.GetAuthorByID)
} }