44 lines
821 B
Go
44 lines
821 B
Go
package author
|
|
|
|
import (
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"tutorial.sqlc.dev/app/internal/author/gen"
|
|
)
|
|
|
|
type Controller struct {
|
|
queries gen.Queries
|
|
}
|
|
|
|
func NewController(conn gen.DBTX) Controller {
|
|
return Controller{
|
|
queries: *gen.New(conn),
|
|
}
|
|
}
|
|
|
|
func (u *Controller) ListAuthors(c *gin.Context) {
|
|
authors, err := u.queries.ListAuthors(c.Request.Context())
|
|
if err != nil {
|
|
c.AbortWithError(500, err)
|
|
return
|
|
}
|
|
c.JSON(200, toAuthorSlice(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, toAuthor(author))
|
|
}
|