ch some
This commit is contained in:
63
internal/shared/assoc.go
Normal file
63
internal/shared/assoc.go
Normal file
@@ -0,0 +1,63 @@
|
||||
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"))
|
||||
}
|
||||
111
internal/shared/flexible.go
Normal file
111
internal/shared/flexible.go
Normal file
@@ -0,0 +1,111 @@
|
||||
package shared
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type FlexibleTime time.Time
|
||||
|
||||
func (t FlexibleTime) Time() time.Time { return time.Time(t) }
|
||||
|
||||
func (t FlexibleTime) IsZero() bool { return time.Time(t).IsZero() }
|
||||
|
||||
func (t FlexibleTime) MarshalJSON() ([]byte, error) {
|
||||
return time.Time(t).MarshalJSON()
|
||||
}
|
||||
|
||||
func (t *FlexibleTime) UnmarshalJSON(b []byte) error {
|
||||
*t = FlexibleTime{}
|
||||
raw := strings.TrimSpace(string(b))
|
||||
if raw == "" || raw == "null" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var n json.Number
|
||||
if err := json.Unmarshal(b, &n); err == nil {
|
||||
s := n.String()
|
||||
if parsed, ok := parseFlexibleTime(s); ok {
|
||||
*t = parsed
|
||||
return nil
|
||||
}
|
||||
if unix, err := n.Int64(); err == nil && unix > 0 {
|
||||
*t = FlexibleTime(time.Unix(unix, 0).UTC())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return nil
|
||||
}
|
||||
if parsed, ok := parseFlexibleTime(s); ok {
|
||||
*t = parsed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseFlexibleTime(s string) (FlexibleTime, bool) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return FlexibleTime{}, false
|
||||
}
|
||||
switch strings.ToLower(s) {
|
||||
case "string", "undefined", "null", "none", "invalid", "nan", "-":
|
||||
return FlexibleTime{}, false
|
||||
}
|
||||
for _, layout := range []string{
|
||||
time.RFC3339Nano,
|
||||
time.RFC3339,
|
||||
"2006-01-02T15:04:05Z07:00",
|
||||
"2006-01-02T15:04:05.000Z",
|
||||
"2006-01-02T15:04:05",
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02",
|
||||
"02.01.2006",
|
||||
"02/01/2006",
|
||||
"02-01-2006",
|
||||
"2006/01/02",
|
||||
"20060102",
|
||||
} {
|
||||
if parsed, err := time.Parse(layout, s); err == nil {
|
||||
return FlexibleTime(parsed), true
|
||||
}
|
||||
}
|
||||
return FlexibleTime{}, false
|
||||
}
|
||||
|
||||
type FlexibleInt64 int64
|
||||
|
||||
func (n FlexibleInt64) Int64() int64 { return int64(n) }
|
||||
|
||||
func (n *FlexibleInt64) UnmarshalJSON(b []byte) error {
|
||||
if string(b) == "null" {
|
||||
*n = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
var v int64
|
||||
if err := json.Unmarshal(b, &v); err == nil {
|
||||
*n = FlexibleInt64(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
*n = 0
|
||||
return nil
|
||||
}
|
||||
v, err := strconv.ParseInt(s, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*n = FlexibleInt64(v)
|
||||
return nil
|
||||
}
|
||||
66
internal/shared/http.go
Normal file
66
internal/shared/http.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package shared
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultPage = 1
|
||||
DefaultLimit = 10
|
||||
MaxLimit = 100
|
||||
)
|
||||
|
||||
func ParseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func QueryValue(c *gin.Context, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func OptionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
|
||||
raw := QueryValue(c, keys...)
|
||||
if raw == "" {
|
||||
return nil, true
|
||||
}
|
||||
id, ok := ParseID(raw)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return &id, true
|
||||
}
|
||||
|
||||
func ParsePageLimit(c *gin.Context) (page, limit int, ok bool) {
|
||||
page = DefaultPage
|
||||
limit = DefaultLimit
|
||||
|
||||
if raw := QueryValue(c, "page"); raw != "" {
|
||||
p, err := strconv.Atoi(raw)
|
||||
if err != nil || p < 1 {
|
||||
return 0, 0, false
|
||||
}
|
||||
page = p
|
||||
}
|
||||
|
||||
if raw := QueryValue(c, "limit"); raw != "" {
|
||||
l, err := strconv.Atoi(raw)
|
||||
if err != nil || l < 1 || l > MaxLimit {
|
||||
return 0, 0, false
|
||||
}
|
||||
limit = l
|
||||
}
|
||||
|
||||
return page, limit, true
|
||||
}
|
||||
11
internal/shared/query.go
Normal file
11
internal/shared/query.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package shared
|
||||
|
||||
import "strings"
|
||||
|
||||
// LikePattern escapes SQL LIKE metacharacters and wraps term for a %term% match.
|
||||
func LikePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return "%" + term + "%"
|
||||
}
|
||||
42
internal/shared/sql.go
Normal file
42
internal/shared/sql.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package shared
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const UserDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')`
|
||||
|
||||
const UserInfoSQL = UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
|
||||
func PrefixedColumns(alias string, cols []string) string {
|
||||
parts := make([]string, len(cols))
|
||||
for i, col := range cols {
|
||||
parts[i] = alias + "." + col
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
func UnmarshalLocalized(raw []byte, dest *LocalizedText) error {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(raw, dest)
|
||||
}
|
||||
|
||||
func OptionalTime(t *FlexibleTime) *time.Time {
|
||||
if t == nil || t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
tt := t.Time()
|
||||
return &tt
|
||||
}
|
||||
|
||||
func OptionalInt64(n *FlexibleInt64) *int64 {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
v := n.Int64()
|
||||
return &v
|
||||
}
|
||||
32
internal/shared/types.go
Normal file
32
internal/shared/types.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package shared
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type UserInfo struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Username string `json:"username"`
|
||||
Phone string `json:"phone"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
type NamedInfo struct {
|
||||
Id int64 `json:"id"`
|
||||
Name LocalizedText `json:"name"`
|
||||
}
|
||||
|
||||
// TextInfo is for catalog rows whose name is a plain string (not localized JSON).
|
||||
type TextInfo struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type BranchInfo struct {
|
||||
Id int64 `json:"id"`
|
||||
Name LocalizedText `json:"name"`
|
||||
UniqueCode string `json:"uniqueCode,omitempty"`
|
||||
}
|
||||
Reference in New Issue
Block a user