| | |
| | | |
| | | import ( |
| | | "apsClient/pkg/snowflake" |
| | | "encoding/json" |
| | | "github.com/jinzhu/gorm" |
| | | "strconv" |
| | | "time" |
| | | ) |
| | | |
| | | type CommonModel struct { |
| | | ID uint `gorm:"primary_key;autoIncrement:false" json:"-"` |
| | | IDStr string `json:"ID" gorm:"-"` |
| | | ID uint `gorm:"primary_key" json:"ID,string"` |
| | | CreatedAt time.Time |
| | | UpdatedAt time.Time |
| | | DeletedAt *time.Time `sql:"index"` |
| | | } |
| | | |
| | | func (c *CommonModel) BeforeCreate(db *gorm.DB) { |
| | | func (c *CommonModel) BeforeCreate() { |
| | | if c.ID == 0 { |
| | | id := snowflake.GenerateID() |
| | | if id < 0 { |
| | | id = snowflake.GenerateID() |
| | | } |
| | | c.ID = uint(id) |
| | | c.ID = uint(snowflake.GenerateID()) |
| | | } |
| | | } |
| | | func (c CommonModel) UnmarshalJSON(b []byte) (err error) { |
| | | id, err := strconv.ParseUint(c.IDStr, 10, 64) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | c.ID = uint(id) |
| | | return |
| | | } |
| | | |
| | | func (c CommonModel) MarshalJSON() ([]byte, error) { |
| | | c.IDStr = strconv.FormatUint(uint64(c.ID), 10) |
| | | return json.Marshal(c) |
| | | } |