diff --git a/backend/errs/validate.go b/backend/errs/validate.go new file mode 100644 index 00000000..661a1f1d --- /dev/null +++ b/backend/errs/validate.go @@ -0,0 +1,5 @@ +package errs + +import "errors" + +var ErrAtLeastOne = errors.New("at least one field must be provided") diff --git a/backend/utilities/merge.go b/backend/utilities/merge.go new file mode 100644 index 00000000..bdb556dd --- /dev/null +++ b/backend/utilities/merge.go @@ -0,0 +1,26 @@ +package utilities + +import "reflect" + +// Merge merges two structs of the same type such that non-zero values from the updated struct take precedence. +func Merge[T any](existing T, updated T) T { + existingVal := reflect.ValueOf(&existing).Elem() + updatedVal := reflect.ValueOf(updated) + + for i := 0; i < existingVal.NumField(); i++ { + existingField := existingVal.Field(i) + updatedField := updatedVal.Field(i) + + // Check if the updated field is non-zero + if !isZeroValue(updatedField) { + existingField.Set(updatedField) + } + } + + return existing +} + +// isZeroValue checks if a reflect.Value is the zero value for its type +func isZeroValue(v reflect.Value) bool { + return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) +}