Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package controller
- import (
- "challenge-goapi/model"
- "challenge-goapi/usecase"
- "net/http"
- "github.com/gin-gonic/gin"
- )
- type CustomerController struct {
- useCase usecase.CustomerUseCase
- rg *gin.RouterGroup
- }
- func (c *CustomerController) createNewCustomer(g *gin.Context) {
- var payload model.Customer
- if err := g.ShouldBindJSON(&payload); err != nil {
- g.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
- return
- }
- customer, err := c.useCase.CreateNewCustomer(payload)
- if err != nil {
- g.JSON(http.StatusInternalServerError, gin.H{"err": "Failed to create new customer"})
- return
- }
- g.JSON(http.StatusCreated, customer)
- }
- func (c *CustomerController) getAllCustomer(g *gin.Context) {
- customers, err := c.useCase.FindAllCustomer()
- if err != nil {
- g.JSON(http.StatusInternalServerError, gin.H{"err": "Failed to retrieve data customers"})
- return
- }
- if len(customers) > 0 {
- g.JSON(http.StatusOK, customers)
- return
- }
- g.JSON(http.StatusOK, gin.H{"message": "List customers empty"})
- }
- func (c *CustomerController) getCustomerById(g *gin.Context) {
- id := g.Param("id")
- customer, err := c.useCase.FindCustomerById(id)
- if err != nil {
- g.JSON(http.StatusInternalServerError, gin.H{"err": "Failed to get customer by ID"})
- return
- }
- g.JSON(http.StatusOK, customer)
- }
- func (c *CustomerController) updateCustomer(g *gin.Context) {
- var payload model.Customer
- if err := g.ShouldBindJSON(&payload); err != nil {
- g.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
- return
- }
- customer, err := c.useCase.UpdateCustomer(payload)
- if err != nil {
- g.JSON(http.StatusInternalServerError, gin.H{"err": err.Error()})
- return
- }
- g.JSON(http.StatusOK, customer)
- }
- func (c *CustomerController) deleteCustomer(g *gin.Context) {
- id := g.Param("id")
- err := c.useCase.DeleteCustomer(id)
- if err != nil {
- g.JSON(http.StatusInternalServerError, gin.H{"err": err.Error()})
- return
- }
- g.JSON(http.StatusOK, nil)
- }
- func (c *CustomerController) Route() {
- c.rg.POST("/customers", c.createNewCustomer)
- c.rg.GET("/customers", c.getAllCustomer)
- c.rg.GET("/customers/:id", c.getCustomerById)
- c.rg.PUT("/customers", c.updateCustomer)
- c.rg.DELETE("/customers/:id", c.deleteCustomer)
- }
- func NewCustomerController(useCase usecase.CustomerUseCase, rg *gin.RouterGroup) *CustomerController {
- return &CustomerController{useCase: useCase, rg: rg}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement