64 lines
2.0 KiB
Go
64 lines
2.0 KiB
Go
package shared
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"online-back/internal/appresult"
|
|
"online-back/pkg/logging"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/jackc/pgx/v4"
|
|
)
|
|
|
|
// AssocRepository is the storage contract shared by "association table"
|
|
// modules (role-users, permission-roles, permission-users, ...): a plain
|
|
// upsert-by-create plus a hard delete, with no list/get.
|
|
type AssocRepository[C any, T any] interface {
|
|
Create(ctx context.Context, dto C) (T, error)
|
|
Delete(ctx context.Context, id int64) error
|
|
}
|
|
|
|
// CreateAssoc handles the POST side of the association-table CRUD pattern:
|
|
// bind the body, create/upsert, respond. entityName is used in log lines
|
|
// only (e.g. "role user").
|
|
func CreateAssoc[C any, T any](c *gin.Context, logger *logging.Logger, repo AssocRepository[C, T], entityName string) {
|
|
var dto C
|
|
if err := c.ShouldBindJSON(&dto); err != nil {
|
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
|
return
|
|
}
|
|
|
|
item, err := repo.Create(c.Request.Context(), dto)
|
|
if err != nil {
|
|
logger.Errorf("create %s failed: %v", entityName, err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
|
}
|
|
|
|
// DeleteAssoc handles the DELETE side of the association-table CRUD pattern:
|
|
// parse the id, delete, respond. entityName is used in both the log line and
|
|
// the success message (e.g. "role user" -> "role user removed").
|
|
func DeleteAssoc[C any, T any](c *gin.Context, logger *logging.Logger, repo AssocRepository[C, T], entityName string) {
|
|
id, ok := ParseID(c.Param("id"))
|
|
if !ok {
|
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
|
return
|
|
}
|
|
|
|
if err := repo.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
|
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
|
return
|
|
} else if err != nil {
|
|
logger.Errorf("delete %s failed: %v", entityName, err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, appresult.SuccessWithData(entityName+" removed"))
|
|
}
|