feat: add component_types management functionality

This commit is contained in:
Tran Anh Tuan
2026-05-11 10:15:02 +07:00
parent 7c9a0d4670
commit 50564e9b78
14 changed files with 1468 additions and 1 deletions

View File

@@ -0,0 +1,50 @@
package mapper
import (
"wm-backend/internal/models"
db "wm-backend/sqlc_gen"
"encoding/json"
"github.com/jackc/pgx/v5/pgtype"
)
func ToDomainComponentType(r db.ComponentType) *models.ComponentType {
return &models.ComponentType{
ID: r.ID,
Name: r.Name,
Description: r.Description.String,
Metadata: json.RawMessage(r.Metadata),
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
}
}
func ToModelComponentType(r *models.ComponentType) *db.CreateComponentTypeParams {
return &db.CreateComponentTypeParams{
Name: r.Name,
Description: pgtype.Text{
String: r.Description,
Valid: r.Description != "",
},
Metadata: []byte(r.Metadata),
CreatedAt: r.CreatedAt,
}
}
func ToUpdateModelComponentType(r *models.ComponentType) *db.UpdateComponentTypeParams {
var metadata []byte
if len(r.Metadata) > 0 {
metadata = []byte(r.Metadata)
}
return &db.UpdateComponentTypeParams{
Name: r.Name,
Description: pgtype.Text{
String: r.Description,
Valid: r.Description != "",
},
Metadata: metadata,
UpdatedAt: r.UpdatedAt,
ID: r.ID,
}
}

View File

@@ -0,0 +1,15 @@
package models
import (
"encoding/json"
"time"
)
type ComponentType struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Metadata json.RawMessage `json:"metadata"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}

View File

@@ -0,0 +1,15 @@
package requests
import "encoding/json"
type CreateComponentTypeRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
Metadata json.RawMessage `json:"metadata"`
}
type UpdateComponentTypeRequest struct {
Name string `json:"name"`
Description string `json:"description"`
Metadata json.RawMessage `json:"metadata"`
}

View File

@@ -0,0 +1,11 @@
package responses
type CreateComponentTypeResponse struct {
ID int64 `json:"id"`
}
type UpdateComponentTypeResponse struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
}

View File

@@ -0,0 +1,52 @@
package repositories
import (
"context"
"wm-backend/internal/mapper"
"wm-backend/internal/models"
db "wm-backend/sqlc_gen"
)
func CreateComponentType(ctx context.Context, queries *db.Queries, body models.ComponentType) (models.ComponentType, error) {
result, err := queries.CreateComponentType(ctx, *mapper.ToModelComponentType(&body))
if err != nil {
return models.ComponentType{}, err
}
return *mapper.ToDomainComponentType(result), nil
}
func GetComponentTypeByID(ctx context.Context, queries *db.Queries, id int64) (models.ComponentType, error) {
result, err := queries.GetComponentTypeByID(ctx, id)
if err != nil {
return models.ComponentType{}, err
}
return *mapper.ToDomainComponentType(result), nil
}
func ListComponentTypes(ctx context.Context, queries *db.Queries) ([]models.ComponentType, error) {
results, err := queries.ListComponentTypes(ctx)
if err != nil {
return nil, err
}
var items []models.ComponentType
for _, r := range results {
items = append(items, *mapper.ToDomainComponentType(r))
}
return items, nil
}
func UpdateComponentType(ctx context.Context, queries *db.Queries, body models.ComponentType) (models.ComponentType, error) {
result, err := queries.UpdateComponentType(ctx, *mapper.ToUpdateModelComponentType(&body))
if err != nil {
return models.ComponentType{}, err
}
return *mapper.ToDomainComponentType(result), nil
}
func DeleteComponentType(ctx context.Context, queries *db.Queries, id int64) (int64, error) {
rowsAffected, err := queries.DeleteComponentType(ctx, id)
if err != nil {
return rowsAffected, err
}
return rowsAffected, nil
}

View File

@@ -73,6 +73,15 @@ func NewRouter() *gin.Engine {
container.PUT("/:id", utils.AsyncHandler(services.ContainerUpdate))
container.DELETE("/:id", utils.AsyncHandler(services.ContainerDelete))
}
componentType := v1.Group(constants.API_GROUP_COMPONENT_TYPE)
{
componentType.GET("", utils.AsyncHandler(services.ComponentTypeList))
componentType.GET("/:id", utils.AsyncHandler(services.ComponentTypeGetByID))
componentType.POST("", utils.AsyncHandler(services.ComponentTypeCreate))
componentType.PUT("/:id", utils.AsyncHandler(services.ComponentTypeUpdate))
componentType.DELETE("/:id", utils.AsyncHandler(services.ComponentTypeDelete))
}
}
r.GET(constants.API_PATH_PING, services.PingHandler)

View File

@@ -0,0 +1,186 @@
package services
import (
"net/http"
"strconv"
"time"
"wm-backend/global"
"wm-backend/internal/models"
"wm-backend/internal/models/requests"
"wm-backend/internal/models/responses"
"wm-backend/internal/repositories"
"wm-backend/pkg/helper"
"wm-backend/response"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
)
// ComponentTypeCreate creates a new component type.
// It validates the request body and creates the component type in the database.
//
// @Summary Create a new component type
// @Description Create a new component type with the provided details
// @Tags component-type
// @Accept json
// @Produce json
// @Param body body requests.CreateComponentTypeRequest true "Component type request body"
// @Success 201 {object} response.SuccessResponse{data=responses.CreateComponentTypeResponse}
// @Failure 400 {object} response.ErrorResponse
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/component-types [post]
func ComponentTypeCreate(c *gin.Context) error {
requestBody := requests.CreateComponentTypeRequest{}
if helper.IsShouldBindJSON(c, &requestBody) {
return nil
}
componentTypeModel := &models.ComponentType{
Name: requestBody.Name,
Description: requestBody.Description,
Metadata: requestBody.Metadata,
CreatedAt: time.Now(),
}
componentType, err := repositories.CreateComponentType(c.Request.Context(), global.Queries, *componentTypeModel)
if err != nil {
response.InternalServerError(c, http.StatusInternalServerError, "Failed to create component type")
return nil
}
response.Created(c, "Component type created successfully", &responses.CreateComponentTypeResponse{
ID: componentType.ID,
})
return nil
}
// ComponentTypeGetByID retrieves a single component type by its ID.
//
// @Summary Get component type by ID
// @Description Retrieve a single component type using its unique identifier
// @Tags component-type
// @Accept json
// @Produce json
// @Param id path int true "Component type ID"
// @Success 200 {object} response.SuccessResponse{data=models.ComponentType}
// @Failure 400 {object} response.ErrorResponse
// @Failure 404 {object} response.ErrorResponse
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/component-types/{id} [get]
func ComponentTypeGetByID(c *gin.Context) error {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequestError(c, http.StatusBadRequest, "Invalid ID")
return nil
}
componentType, err := repositories.GetComponentTypeByID(c.Request.Context(), global.Queries, id)
if err != nil {
response.NotFoundError(c, http.StatusNotFound, "Component type not found")
return nil
}
response.Ok(c, "Success", componentType)
return nil
}
// ComponentTypeList retrieves all component types.
//
// @Summary List all component types
// @Description Retrieve a list of all component types ordered by creation date
// @Tags component-type
// @Accept json
// @Produce json
// @Success 200 {object} response.SuccessResponse{data=[]models.ComponentType}
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/component-types [get]
func ComponentTypeList(c *gin.Context) error {
componentTypes, err := repositories.ListComponentTypes(c.Request.Context(), global.Queries)
if err != nil {
response.InternalServerError(c, http.StatusInternalServerError, "Failed to list component types")
return nil
}
response.Ok(c, "Success", componentTypes)
return nil
}
// ComponentTypeUpdate updates an existing component type by its ID.
// It validates the request body, fetches the existing record,
// merges non-empty fields from the request, and updates the component type in the database.
//
// @Summary Update component type
// @Description Update an existing component type by its ID. Only non-empty fields will be updated.
// @Tags component-type
// @Accept json
// @Produce json
// @Param id path int true "Component type ID"
// @Param body body requests.UpdateComponentTypeRequest true "Component type request body"
// @Success 200 {object} response.SuccessResponse{data=responses.UpdateComponentTypeResponse}
// @Failure 400 {object} response.ErrorResponse
// @Failure 404 {object} response.ErrorResponse
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/component-types/{id} [put]
func ComponentTypeUpdate(c *gin.Context) error {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequestError(c, http.StatusBadRequest, "Invalid ID")
return nil
}
requestBody := requests.UpdateComponentTypeRequest{}
if helper.IsShouldBindJSON(c, &requestBody) {
return nil
}
existing, err := repositories.GetComponentTypeByID(c.Request.Context(), global.Queries, id)
if err != nil {
response.NotFoundError(c, http.StatusNotFound, "Component type not found")
return nil
}
if requestBody.Name != "" {
existing.Name = requestBody.Name
}
if requestBody.Description != "" {
existing.Description = requestBody.Description
}
if len(requestBody.Metadata) > 0 {
existing.Metadata = requestBody.Metadata
}
existing.UpdatedAt = time.Now()
componentType, err := repositories.UpdateComponentType(c.Request.Context(), global.Queries, existing)
if err != nil {
response.InternalServerError(c, http.StatusInternalServerError, "Failed to update component type")
return nil
}
response.Ok(c, "Component type updated successfully", &responses.UpdateComponentTypeResponse{
ID: componentType.ID,
Name: componentType.Name,
Description: componentType.Description,
})
return nil
}
// ComponentTypeDelete deletes a component type by its ID.
//
// @Summary Delete component type
// @Description Delete a component type by its unique identifier
// @Tags component-type
// @Accept json
// @Produce json
// @Param id path int true "Component type ID"
// @Success 200 {object} response.SuccessResponse
// @Failure 400 {object} response.ErrorResponse
// @Failure 500 {object} response.ErrorResponse
// @Router /api/v1/component-types/{id} [delete]
func ComponentTypeDelete(c *gin.Context) error {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequestError(c, http.StatusBadRequest, "Invalid ID")
return nil
}
rowsAffected, err := repositories.DeleteComponentType(c.Request.Context(), global.Queries, id)
if err != nil {
log.Error().Err(err).Msgf("Failed to delete component type with ID: %d", id)
response.InternalServerError(c, http.StatusInternalServerError, "Failed to delete component type")
return nil
}
if rowsAffected == 0 {
response.NotFoundError(c, http.StatusNotFound, "Component type not found")
return nil
}
response.Ok(c, "Delete Success", nil)
return nil
}