refactor: change SaveUpload to use gorm create or selective Updates

This commit is contained in:
Derrick Hammer 2024-02-17 23:39:51 -05:00
parent 8f78f6fe87
commit 9e35c614e3
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 40 additions and 10 deletions

View File

@ -77,22 +77,52 @@ func (m *MetadataServiceDefault) SaveUpload(ctx context.Context, metadata Upload
ret := m.db.WithContext(ctx).Model(&models.Upload{}).Where(&upload).First(&upload) ret := m.db.WithContext(ctx).Model(&models.Upload{}).Where(&upload).First(&upload)
if ret.Error != nil { if ret.Error != nil {
if !errors.Is(ret.Error, gorm.ErrRecordNotFound) { if errors.Is(ret.Error, gorm.ErrRecordNotFound) && ret.RowsAffected > 0 {
return ret.Error return m.createUpload(ctx, metadata)
} }
return ret.Error
} }
if ret.RowsAffected > 0 { changed := false
return nil
if upload.UserID != metadata.UserID {
changed = true
} }
upload.UserID = metadata.UserID if upload.MimeType != metadata.MimeType {
upload.MimeType = metadata.MimeType changed = true
upload.Protocol = metadata.Protocol }
upload.UploaderIP = metadata.UploaderIP
upload.Size = metadata.Size
return m.db.Save(&metadata).Error if upload.Protocol != metadata.Protocol {
changed = true
}
if upload.UploaderIP != metadata.UploaderIP {
changed = true
}
if upload.Size != metadata.Size {
changed = true
}
if changed {
return m.db.Updates(&upload).Error
}
return nil
}
func (m *MetadataServiceDefault) createUpload(ctx context.Context, metadata UploadMetadata) error {
upload := models.Upload{
UserID: metadata.UserID,
Hash: metadata.Hash,
MimeType: metadata.MimeType,
Protocol: metadata.Protocol,
UploaderIP: metadata.UploaderIP,
Size: metadata.Size,
}
return m.db.WithContext(ctx).Create(&upload).Error
} }
func (m *MetadataServiceDefault) GetUpload(ctx context.Context, objectHash []byte) (UploadMetadata, error) { func (m *MetadataServiceDefault) GetUpload(ctx context.Context, objectHash []byte) (UploadMetadata, error) {