fix(idgen): retry snowflake generation and error on negative ID

NextUint64ID now retries up to 3 times when Int64() is negative, then
returns an error instead of 0 or Fatalf. All call sites propagate the
error to avoid GORM omitting zero-value primary keys.
This commit is contained in:
ryan
2026-06-17 13:08:00 +08:00
parent a27113feb2
commit 92dc6a59c0
11 changed files with 145 additions and 44 deletions
+19 -6
View File
@@ -4,7 +4,8 @@
package user
import ("net/http"
import (
"net/http"
"strconv"
"strings"
"time"
@@ -17,7 +18,8 @@ import ("net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"github.com/Rain-kl/Wavelet/internal/common/response")
"github.com/Rain-kl/Wavelet/internal/common/response"
)
// minPasswordLength 密码最小长度
const minPasswordLength = 8
@@ -31,7 +33,7 @@ type listUsersRequest struct {
}
type user struct {
ID uint64 `json:"id"`
ID uint64 `json:"id,string"`
Username string `json:"username"`
Nickname string `json:"nickname"`
Email string `json:"email"`
@@ -104,7 +106,7 @@ func ListUsers(c *gin.Context) {
return
}
var users []user
var modelUsers []model.User
var total int64
query := db.DB(c.Request.Context()).Model(&model.User{})
@@ -131,11 +133,16 @@ func ListUsers(c *gin.Context) {
Order("id DESC").
Offset(offset).
Limit(req.PageSize).
Find(&users).Error; err != nil {
Find(&modelUsers).Error; err != nil {
c.JSON(http.StatusInternalServerError, response.Err(err.Error()))
return
}
users := make([]user, 0, len(modelUsers))
for _, modelUser := range modelUsers {
users = append(users, toUser(modelUser))
}
c.JSON(http.StatusOK, response.OK(listUsersResponse{
Users: users,
Total: total,
@@ -379,8 +386,14 @@ func CreateUser(c *gin.Context) {
return
}
nextID, err := idgen.NextUint64ID()
if err != nil {
c.JSON(http.StatusInternalServerError, response.Err(createUserFailed))
return
}
newUser := model.User{
ID: idgen.NextUint64ID(),
ID: nextID,
Username: req.Username,
Nickname: req.Nickname,
Email: req.Email,