flamingo.me/flamingo-commerce/v3@v3.11.0/product/interfaces/controller/apicontroller.go (about)

     1  package controller
     2  
     3  import (
     4  	"context"
     5  
     6  	"flamingo.me/flamingo/v3/framework/web"
     7  	"github.com/pkg/errors"
     8  
     9  	"flamingo.me/flamingo-commerce/v3/product/application"
    10  	"flamingo.me/flamingo-commerce/v3/product/domain"
    11  )
    12  
    13  type (
    14  	// APIController for products
    15  	APIController struct {
    16  		responder      *web.Responder
    17  		productService domain.ProductService
    18  		uRLService     *application.URLService
    19  	}
    20  
    21  	// APIResult view data
    22  	APIResult struct {
    23  		Error   *resultError
    24  		Success bool
    25  		Product domain.BasicProduct
    26  	}
    27  
    28  	resultError struct {
    29  		Message string
    30  		Code    string
    31  	} //@name productResultError
    32  )
    33  
    34  // Inject dependencies
    35  func (c *APIController) Inject(responder *web.Responder,
    36  	productService domain.ProductService,
    37  	uRLService *application.URLService) *APIController {
    38  	c.responder = responder
    39  	c.productService = productService
    40  	c.uRLService = uRLService
    41  	return c
    42  }
    43  
    44  // Get Response for Product matching marketplacecode param
    45  // @Summary Gets the requested product
    46  // @Tags  Product
    47  // @Produce json
    48  // @Success 200 {object} APIResult{product=domain.SimpleProduct}
    49  // @Failure 500 {object} APIResult
    50  // @Failure 404 {object} APIResult
    51  // @Param marketplacecode path string true "the marketplace code (idendifier) for the product"
    52  // @Router /api/v1/products/{marketplacecode} [get]
    53  func (c *APIController) Get(ctx context.Context, r *web.Request) web.Result {
    54  	product, err := c.productService.Get(ctx, r.Params["marketplacecode"])
    55  	if err != nil {
    56  		switch errors.Cause(err).(type) {
    57  		case domain.ProductNotFound:
    58  			return c.responder.Data(APIResult{
    59  				Success: false,
    60  				Error:   &resultError{Code: "404", Message: err.Error()},
    61  			})
    62  
    63  		default:
    64  			return c.responder.Data(APIResult{
    65  				Success: false,
    66  				Error:   &resultError{Code: "500", Message: err.Error()},
    67  			})
    68  		}
    69  	}
    70  
    71  	return c.responder.Data(APIResult{
    72  		Success: true,
    73  		Product: product,
    74  	})
    75  }