/
model.go
46 lines (38 loc) · 1.39 KB
/
model.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package models
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
// DefaultModel is the base model for most models in Envelope Zero.
// As EnvelopeMonth uses the Envelope ID and the Month as primary key,
// we the timestamps are managed in the Timestamps struct.
type DefaultModel struct {
ID uuid.UUID `json:"id" example:"65392deb-5e92-4268-b114-297faad6cdce"`
Timestamps
}
// Timestamps only contains the timestamps that gorm sets automatically to enable other
// primary keys than ID.
type Timestamps struct {
CreatedAt time.Time `json:"createdAt" example:"2022-04-02T19:28:44.491514Z"`
UpdatedAt time.Time `json:"updatedAt" example:"2022-04-17T20:14:01.048145Z"`
DeletedAt *gorm.DeletedAt `json:"deletedAt" gorm:"index" example:"2022-04-22T21:01:05.058161Z" swaggertype:"primitive,string"`
}
// AfterFind updates the timestamps to use UTC as
// timezone, not +0000. Yes, this is different.
//
// We already store them in UTC, but somehow reading
// them from the database returns them as +0000.
func (m *DefaultModel) AfterFind(tx *gorm.DB) (err error) {
m.CreatedAt = m.CreatedAt.In(time.UTC)
m.UpdatedAt = m.UpdatedAt.In(time.UTC)
if m.DeletedAt != nil {
m.DeletedAt.Time = m.DeletedAt.Time.In(time.UTC)
}
return nil
}
// BeforeCreate is set to generate a UUID for the resource.
func (m *DefaultModel) BeforeCreate(tx *gorm.DB) (err error) {
m.ID = uuid.New()
return nil
}