package database import ( "fmt" "git.tovijaeschke.xyz/tovi/JumboPetstore/models" "git.tovijaeschke.xyz/tovi/JumboPetstore/util" "gorm.io/gorm" "gorm.io/gorm/clause" ) func CreatePet(petData *models.Pet) error { var ( photoUrls []string photoUrl string fileName string err error ) for _, photoUrl = range petData.PhotoUrlJson { fileName, err = util.DownloadFile(photoUrl) if err != nil { return err } petData.PhotoUrls = append(petData.PhotoUrls, models.PetPhoto{ PetId: petData.Id, FileName: fileName, }) photoUrls = append(photoUrls, fmt.Sprintf( "/images/%s", fileName, )) } petData.PhotoUrlJson = photoUrls err = DB.Session(&gorm.Session{FullSaveAssociations: true}). Omit("PhotoUrlJson"). Create(petData). Error if err != nil { return err } return err } func UpdatePet(petData *models.Pet) error { var ( photoUrls []string photoUrl string fileName string err error ) for _, photoUrl = range petData.PhotoUrlJson { fileName, err = util.DownloadFile(photoUrl) if err != nil { return err } petData.PhotoUrls = append(petData.PhotoUrls, models.PetPhoto{ PetId: petData.Id, FileName: fileName, }) photoUrls = append(photoUrls, fmt.Sprintf( "/images/%s", fileName, )) } petData.PhotoUrlJson = photoUrls // This leaves some orphaned files in ./uploads DB.Model(petData).Association("PhotoUrls").Replace(petData.PhotoUrls) DB.Model(petData).Association("Tags").Replace(petData.Tags) err = DB.Session(&gorm.Session{FullSaveAssociations: true}). Omit("PhotoUrlJson"). Updates(petData). Error if err != nil { return err } return err } func GetPetById(id int) models.Pet { var ( petData models.Pet petPhoto models.PetPhoto photoUrls []string ) DB.Preload(clause.Associations).First(&petData, "id = ?", id) for _, petPhoto = range petData.PhotoUrls { photoUrls = append(photoUrls, "/images/"+petPhoto.FileName) } petData.PhotoUrlJson = photoUrls return petData } func DeletePet(petData models.Pet) { DB.Preload(clause.Associations).Delete(&petData) } func GetPetsByStatus(status string) ([]models.Pet, error) { var ( petDatas []models.Pet petPhoto models.PetPhoto photoUrls []string i int err error ) err = DB.Preload(clause.Associations). Where("status = ?", status). Find(&petDatas). Error if err != nil { return petDatas, err } for i = range petDatas { photoUrls = []string{} for _, petPhoto = range petDatas[i].PhotoUrls { photoUrls = append(photoUrls, "/images/"+petPhoto.FileName) } petDatas[i].PhotoUrlJson = photoUrls } return petDatas, err } func AddPhotoToPet(petData *models.Pet, fileName string, additionalMetadata string, fileBytes []byte) (string, error) { var ( err error ) fileName, err = util.WriteFile(fileName, fileBytes) petData.PhotoUrls = append(petData.PhotoUrls, models.PetPhoto{ PetId: petData.Id, FileName: fileName, AdditionalMetadata: additionalMetadata, }) err = DB.Session(&gorm.Session{FullSaveAssociations: true}). Omit("PhotoUrlJson"). Updates(&petData). Error return fileName, err }