3

I'm using gorm as a Golang ORM. I need to detect if any model field has changed to trigger a update on a thirdy-party API service.

I have tried to test every field with an If statement, but it gets ugly when the model has many fields.

var person Person

db.Where("id = ?", id).First(&person)

if person.Name != body.Person.Name || person.Age != body.Person.Age {
  // Trigger API update
}

db.Save(&person)

Is there a easy way to achieve this?

2 Answers 2

1

I don't know if this is the simplest way, and it is probably not idiomatic, but you can accomplish this with reflection. The following function uses the reflect Package to compare two Person structs to see if their values for each field are the same, skipping the Model struct (whose internals vary independently of the data element the Person represents).

func (this Person) Equals(that Person) bool {
    vThis := reflect.ValueOf(this)
    vThat := reflect.ValueOf(that)
    for i := 0; i < vThis.NumField(); i++ {
        if vThis.Field(i) != vThis.FieldByName("Model") {
            if vThis.Field(i).Interface() != vThat.Field(i).Interface() {
                return false
            }
        }       
    }
    return true
}

You could use this in your code snippet then as follows:

if !person.Equals(body.Person) {
  // Trigger API update
}

Note that I'm quite new to go, so I may be leading you astray here in terms of "proper" code. But this does work.

1

GORM does provide such a feature via the 'Changed' method which could be used in Before Update Hooks. It returns if the field was changed or not.

https://gorm.io/docs/update.html#Check-Field-has-changed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.