mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
initial commit
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/dto"
|
||||
service "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/services"
|
||||
validation "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/validations"
|
||||
"github.com/hafizhproject45/Golang-Boilerplate.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type UserController struct {
|
||||
UserService service.UserService
|
||||
}
|
||||
|
||||
func NewUserController(userService service.UserService) *UserController {
|
||||
return &UserController{
|
||||
UserService: userService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UserController) GetAll(c *fiber.Ctx) error {
|
||||
query := &validation.Query{
|
||||
Page: c.QueryInt("page", 1),
|
||||
Limit: c.QueryInt("limit", 10),
|
||||
Search: c.Query("search", ""),
|
||||
}
|
||||
|
||||
result, totalResults, err := u.UserService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.UserListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all users successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToUserListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *UserController) GetOne(c *fiber.Ctx) error {
|
||||
param := c.Params("id")
|
||||
|
||||
id, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
|
||||
}
|
||||
|
||||
result, err := u.UserService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get user successfully",
|
||||
Data: dto.ToUserListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *UserController) CreateOne(c *fiber.Ctx) error {
|
||||
req := new(validation.Create)
|
||||
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
|
||||
}
|
||||
|
||||
result, err := u.UserService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create user successfully",
|
||||
Data: dto.ToUserListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *UserController) UpdateOne(c *fiber.Ctx) error {
|
||||
req := new(validation.Update)
|
||||
param := c.Params("id")
|
||||
|
||||
id, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
|
||||
}
|
||||
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
|
||||
}
|
||||
|
||||
result, err := u.UserService.UpdateOne(c, req, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Update user successfully",
|
||||
Data: dto.ToUserListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *UserController) DeleteOne(c *fiber.Ctx) error {
|
||||
param := c.Params("id")
|
||||
|
||||
id, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
|
||||
}
|
||||
|
||||
if err := u.UserService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete user successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
model "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/models"
|
||||
)
|
||||
|
||||
// === DTO Structs ===
|
||||
|
||||
type UserListDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type UserDetailDTO struct {
|
||||
UserListDTO
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToUserListDTO(m model.User) UserListDTO {
|
||||
return UserListDTO{
|
||||
Id: m.Id,
|
||||
Name: m.Name,
|
||||
}
|
||||
}
|
||||
|
||||
func ToUserListDTOs(m []model.User) []UserListDTO {
|
||||
result := make([]UserListDTO, len(m))
|
||||
for i, r := range m {
|
||||
result[i] = ToUserListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Id uint `gorm:"primaryKey"`
|
||||
Name string `gorm:"not null"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rUser "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/repositories"
|
||||
sUser "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type UserModule struct{}
|
||||
|
||||
func (UserModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
UserRoutes(router, userService)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
model "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/models"
|
||||
"github.com/hafizhproject45/Golang-Boilerplate.git/internal/repository"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
repository.BaseRepository[model.User]
|
||||
}
|
||||
|
||||
type UserRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[model.User]
|
||||
}
|
||||
|
||||
func NewUserRepository(db *gorm.DB) UserRepository {
|
||||
return &UserRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[model.User](db),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
controller "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/controllers"
|
||||
user "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func UserRoutes(v1 fiber.Router, s user.UserService) {
|
||||
ctrl := controller.NewUserController(s)
|
||||
|
||||
route := v1.Group("/users")
|
||||
|
||||
route.Get("/", ctrl.GetAll)
|
||||
route.Post("/", ctrl.CreateOne)
|
||||
route.Get("/:id", ctrl.GetOne)
|
||||
route.Patch("/:id", ctrl.UpdateOne)
|
||||
route.Delete("/:id", ctrl.DeleteOne)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
model "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/models"
|
||||
repository "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/repositories"
|
||||
validation "github.com/hafizhproject45/Golang-Boilerplate.git/internal/modules/users/validations"
|
||||
"github.com/hafizhproject45/Golang-Boilerplate.git/internal/utils"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]model.User, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*model.User, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*model.User, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*model.User, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
}
|
||||
|
||||
type userService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(repo repository.UserRepository, validate *validator.Validate) UserService {
|
||||
return &userService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
func (s userService) GetAll(c *fiber.Ctx, params *validation.Query) ([]model.User, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
users, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
|
||||
if params.Search != "" {
|
||||
return db.Where("name LIKE ?", "%"+params.Search+"%")
|
||||
}
|
||||
return db.Order("created_at DESC").Order("updated_at DESC")
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to get users: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return users, total, nil
|
||||
}
|
||||
|
||||
func (s userService) GetOne(c *fiber.Ctx, id uint) (*model.User, error) {
|
||||
user, err := s.Repository.GetByID(c.Context(), id, nil)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "User not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get user by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *userService) CreateOne(c *fiber.Ctx, req *validation.Create) (*model.User, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
createBody := &model.User{
|
||||
Name: req.Name,
|
||||
}
|
||||
|
||||
if err := s.Repository.CreateOne(c.Context(), createBody, nil); err != nil {
|
||||
s.Log.Errorf("Failed to create user: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return createBody, nil
|
||||
}
|
||||
|
||||
func (s userService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*model.User, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
if req.Name != nil {
|
||||
updateBody["name"] = *req.Name
|
||||
}
|
||||
|
||||
if err := s.Repository.PatchOne(c.Context(), id, updateBody, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "User not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update user: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s userService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
if err := s.Repository.DeleteOne(c.Context(), id); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "User not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete user: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,max=50"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
Page int `query:"page" validate:"omitempty,number,min=1"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100"`
|
||||
Search string `query:"search" validate:"omitempty,max=50"`
|
||||
}
|
||||
Reference in New Issue
Block a user