Refactor server code (#407)

This commit is contained in:
Thomas Miceli
2025-01-20 01:57:39 +01:00
committed by GitHub
parent 4c5a7bda63
commit f935ee1a7e
69 changed files with 4357 additions and 3337 deletions

View File

@ -1,6 +1,7 @@
package db
import (
"github.com/thomiceli/opengist/internal/git"
"gorm.io/gorm"
)
@ -25,31 +26,36 @@ type User struct {
}
func (user *User) BeforeDelete(tx *gorm.DB) error {
// Decrement likes counter for all gists liked by this user
// The likes will be automatically deleted by the foreign key constraint
err := tx.Model(&Gist{}).
Omit("updated_at").
Where("id IN (?)", tx.
Select("gist_id").
Table("likes").
Where("user_id = ?", user.ID),
).
UpdateColumn("nb_likes", gorm.Expr("nb_likes - 1")).
Error
// Decrement likes counter using derived table
err := tx.Exec(`
UPDATE gists
SET nb_likes = nb_likes - 1
WHERE id IN (
SELECT gist_id
FROM (
SELECT gist_id
FROM likes
WHERE user_id = ?
) AS derived_likes
)
`, user.ID).Error
if err != nil {
return err
}
// Decrement forks counter for all gists forked by this user
err = tx.Model(&Gist{}).
Omit("updated_at").
Where("id IN (?)", tx.
Select("forked_id").
Table("gists").
Where("user_id = ?", user.ID),
).
UpdateColumn("nb_forks", gorm.Expr("nb_forks - 1")).
Error
// Decrement forks counter using derived table
err = tx.Exec(`
UPDATE gists
SET nb_forks = nb_forks - 1
WHERE id IN (
SELECT forked_id
FROM (
SELECT forked_id
FROM gists
WHERE user_id = ? AND forked_id IS NOT NULL
) AS derived_forks
)
`, user.ID).Error
if err != nil {
return err
}
@ -64,8 +70,17 @@ func (user *User) BeforeDelete(tx *gorm.DB) error {
return err
}
// Delete all gists created by this user
return tx.Where("user_id = ?", user.ID).Delete(&Gist{}).Error
err = tx.Where("user_id = ?", user.ID).Delete(&Gist{}).Error
if err != nil {
return err
}
// Delete user directory
if err = git.DeleteUserDirectory(user.Username); err != nil {
return err
}
return nil
}
func UserExists(username string) (bool, error) {