59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package response
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
type Status string
|
|
|
|
const (
|
|
Error Status = "error"
|
|
Success Status = "success"
|
|
)
|
|
|
|
type APIResponse struct {
|
|
Status Status `json:"status"`
|
|
Message string `json:"message"`
|
|
Data any `json:"data,omitempty" swaggerignore:"true"`
|
|
// Optional endpoint-specific metadata; omitted when there is no metadata.
|
|
Metadata any `json:"metadata,omitempty" swaggertype:"object"`
|
|
Page *int `json:"page,omitempty"`
|
|
Total *int `json:"total,omitempty"`
|
|
Timestamp time.Time `json:"timestamp"`
|
|
}
|
|
|
|
func NewAPIResponse(
|
|
status Status, message string,
|
|
data any, metadata any,
|
|
page *int, total *int,
|
|
) APIResponse {
|
|
|
|
return APIResponse{
|
|
Status: status,
|
|
Message: message,
|
|
Data: data,
|
|
Metadata: metadata,
|
|
Timestamp: time.Now(),
|
|
Page: page,
|
|
Total: total,
|
|
}
|
|
}
|
|
func WriteJSON(c *fiber.Ctx, status int, message string, data, metadata any) error {
|
|
return writeJSON(c, status, message, data, metadata, nil, nil)
|
|
}
|
|
func WritePaginatedJSON(c *fiber.Ctx, status int, message string, data, metadata any, page int, total int) error {
|
|
return writeJSON(c, status, message, data, metadata, &page, &total)
|
|
}
|
|
|
|
func writeJSON(c *fiber.Ctx, status int, message string, data, metadata any, page, total *int) error {
|
|
apiStatus := Error
|
|
if status >= 200 && status <= 299 {
|
|
apiStatus = Success
|
|
}
|
|
apiRes := NewAPIResponse(apiStatus, message, data, metadata, page, total)
|
|
|
|
return c.Status(status).JSON(apiRes)
|
|
}
|