github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/api/controllers/responses.go (about)

     1  package controllers
     2  
     3  import (
     4  	"github.com/labstack/echo/v4"
     5  
     6  	"github.com/e154/smart-home/common"
     7  )
     8  
     9  // Pagination ...
    10  type Pagination struct {
    11  	Page  int64  `json:"page"`
    12  	Total int64  `json:"total"`
    13  	Limit uint64 `json:"limit"`
    14  }
    15  
    16  // GenericMeta ...
    17  type GenericMeta struct {
    18  	Pagination *Pagination `json:"pagination,omitempty"`
    19  	Sort       *string     `json:"sort,omitempty"`
    20  }
    21  
    22  func NewGenericMeta(ctx echo.Context) *GenericMeta {
    23  	return &GenericMeta{}
    24  }
    25  
    26  func (g *GenericMeta) WithPagination(pagination Pagination) *GenericMeta {
    27  	g.Pagination = &pagination
    28  	return g
    29  }
    30  
    31  func (g *GenericMeta) WithSort(sort string) *GenericMeta {
    32  	g.Sort = common.String(sort)
    33  	return g
    34  }
    35  
    36  // ErrorField ...
    37  type ErrorField struct {
    38  	Name    *string `json:"name,omitempty"`
    39  	Message *string `json:"message,omitempty"`
    40  }
    41  
    42  // ErrorBase ...
    43  type ErrorBase struct {
    44  	Code    *string      `json:"code,omitempty"`
    45  	Message *string      `json:"message,omitempty"`
    46  	Fields  []ErrorField `json:"fields,omitempty"`
    47  }
    48  
    49  // Error ...
    50  type Error struct {
    51  	Error *ErrorBase   `json:"error,omitempty"`
    52  	Meta  *GenericMeta `json:"meta,omitempty"`
    53  }
    54  
    55  // Data ...
    56  type Data struct {
    57  	ID interface{} `json:"id,omitempty"`
    58  }
    59  
    60  // Success ...
    61  type Success struct {
    62  	Data  interface{}  `json:"data,omitempty"`
    63  	Items interface{}  `json:"items"`
    64  	Meta  *GenericMeta `json:"meta,omitempty"`
    65  }
    66  
    67  // ResponseWithObj ...
    68  func ResponseWithObj(ctx echo.Context, obj interface{}) interface{} {
    69  	return obj
    70  }
    71  
    72  // ResponseWithList ...
    73  func ResponseWithList(ctx echo.Context, items interface{}, total int64, pagination common.PageParams) *Success {
    74  	return &Success{
    75  		Items: items,
    76  		Meta: NewGenericMeta(ctx).
    77  			WithPagination(Pagination{
    78  				Page:  pagination.PageReq,
    79  				Total: total,
    80  				Limit: uint64(pagination.Limit),
    81  			}).
    82  			WithSort(pagination.SortReq),
    83  	}
    84  }
    85  
    86  func ResponseWithError(ctx echo.Context, err *ErrorBase) *Error {
    87  	return &Error{
    88  		Error: err,
    89  	}
    90  }