infoalloggi-monorepo/apps/backend/image_handler.go
Marco Pedone 2725098203 Refactor database handling and queries
- Updated DbHandler to accept configuration parameters instead of using environment variables directly.
- Moved database queries from handler.go to a dedicated queries package for better organization and separation of concerns.
- Implemented error handling in query functions to provide more informative error messages.
- Refactored image handling to utilize the new queries package for database interactions.
- Cleaned up unused code and comments across various files.
- Improved overall code readability and maintainability.
2025-08-22 10:11:07 +02:00

103 lines
2 KiB
Go

package main
import (
"backend/queries"
"backend/typedefs"
"fmt"
"log"
"os"
"path/filepath"
)
type ImageRefManager struct {
}
func NewImageRefManager() *ImageRefManager {
return &ImageRefManager{}
}
// func (i *ImageRefManager) GetImagesRef() ([]typedefs.MiogestImagesRef_Table, error) {
// return queries.ImagesGetAll()
// }
func (i *ImageRefManager) InsertImagesRef(annunci *typedefs.AnnunciXML) error {
return queries.ImagesBatchInsert(annunci)
}
func (i *ImageRefManager) FindIsUpdate(annunci *typedefs.AnnunciXML) ([]string, error) {
r, err := queries.ImagesGetAll()
if err != nil {
return nil, err
}
refMap := make(map[string][]string) // Convert slice to map for faster lookup
for _, ref := range r {
if ref.Foto != nil {
refMap[ref.Codice] = *ref.Foto
}
}
var result []string
for _, annuncio := range annunci.Annuncio {
if annuncio.Codice != nil && annuncio.Foto != nil {
refFoto, exists := refMap[*annuncio.Codice]
if !exists {
fmt.Println("new codice", *annuncio.Codice)
result = append(result, *annuncio.Codice)
continue
}
if len(*annuncio.Foto) != len(refFoto) {
fmt.Println("Different length", *annuncio.Foto, refFoto)
result = append(result, *annuncio.Codice)
continue
}
for i, foto := range *annuncio.Foto {
if foto != refFoto[i] {
fmt.Println("Different content", *annuncio.Foto, refFoto)
result = append(result, *annuncio.Codice)
break
}
}
}
}
return result, nil
}
func (i *ImageRefManager) ClearImages(to_clear []string) error {
for _, codice := range to_clear {
folder := filepath.Join(imgbasepath, codice)
err := os.RemoveAll(folder)
if err != nil {
return err
}
}
return nil
}
func (i *ImageRefManager) Reset() error {
err := queries.ImagesClear()
if err != nil {
return err
}
err = queries.AnnunciResetImages()
if err != nil {
return err
}
err = os.RemoveAll(imgbasepath)
if err != nil {
log.Fatal(err)
}
err = os.Mkdir(imgbasepath, 0755)
if err != nil {
log.Fatal(err)
}
return nil
}