Skip to content
This repository has been archived by the owner on Jun 25, 2024. It is now read-only.

Commit

Permalink
changedFrom field added (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewSafonov authored and sas1024 committed Sep 20, 2017
1 parent 4043097 commit 0ecc0ea
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 13 deletions.
27 changes: 21 additions & 6 deletions callbacks.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

type LoggablePlugin interface {
SetUser(user string) *gorm.DB
SetFrom(from string) *gorm.DB
GetRecords(objectId string) ([]*ChangeLog, error)
}

Expand Down Expand Up @@ -48,6 +49,13 @@ func (r *loggablePlugin) SetUser(user string) *gorm.DB {
return db
}

func (r *loggablePlugin) SetFrom(from string) *gorm.DB {
r.mu.Lock()
db := r.db.Set("loggable:from", from)
r.mu.Unlock()
return db
}

func (r *loggablePlugin) addRecord(scope *gorm.Scope, action string) error {
var jsonObject JSONB
j, err := json.Marshal(scope.Value)
Expand All @@ -62,14 +70,19 @@ func (r *loggablePlugin) addRecord(scope *gorm.Scope, action string) error {
if !ok {
user = ""
}
from, ok := scope.DB().Get("loggable:from")
if !ok {
from = ""
}

cl := ChangeLog{
ID: uuid.NewV4().String(),
ChangedBy: user.(string),
Action: action,
ObjectID: scope.PrimaryKeyValue().(string),
ObjectType: scope.GetModelStruct().ModelType.Name(),
Object: jsonObject,
ID: uuid.NewV4().String(),
ChangedBy: user.(string),
ChangedFrom: from.(string),
Action: action,
ObjectID: scope.PrimaryKeyValue().(string),
ObjectType: scope.GetModelStruct().ModelType.Name(),
Object: jsonObject,
}
err = scope.DB().Create(&cl).Error
if err != nil {
Expand All @@ -91,11 +104,13 @@ func (r *loggablePlugin) addCreated(scope *gorm.Scope) {
r.addRecord(scope, "create")
}
}

func (r *loggablePlugin) addUpdated(scope *gorm.Scope) {
if isLoggable(scope) {
r.addRecord(scope, "update")
}
}

func (r *loggablePlugin) addDeleted(scope *gorm.Scope) {
if isLoggable(scope) {
r.addRecord(scope, "delete")
Expand Down
16 changes: 9 additions & 7 deletions loggable.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,20 @@ import (
)

type ChangeLog struct {
ID string `gorm:"type:uuid;primary_key;"`
CreatedAt time.Time `sql:"DEFAULT:current_timestamp"`
ChangedBy string `gorm:"index"`
Action string
ObjectID string `gorm:"index"`
ObjectType string `gorm:"index"`
Object JSONB `sql:"type:JSONB"`
ID string `gorm:"type:uuid;primary_key;"`
CreatedAt time.Time `sql:"DEFAULT:current_timestamp"`
ChangedBy string `gorm:"index"`
ChangedFrom string `gorm:"index"`
Action string
ObjectID string `gorm:"index"`
ObjectType string `gorm:"index"`
Object JSONB `sql:"type:JSONB"`
}

type loggableInterface interface {
stubMethod() error
}

type LoggableModel struct {
}

Expand Down

0 comments on commit 0ecc0ea

Please sign in to comment.