Skip to content

Commit

Permalink
fix(cache): unable to change admin list after caching (#748) (#750)
Browse files Browse the repository at this point in the history
  • Loading branch information
qwqcode committed Jan 26, 2024
1 parent 50b0a60 commit 9dacd09
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 10 deletions.
13 changes: 4 additions & 9 deletions internal/dao/query_find.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,16 +219,11 @@ func (dao *Dao) GetVoteNumUpDown(targetID uint, voteTo string) (int, int) {
//#endregion

// #region 管理员账号检测
var allAdmins *[]entity.User = nil

func (dao *Dao) GetAllAdmins() []entity.User {
if allAdmins == nil {
var admins []entity.User
dao.DB().Where(&entity.User{IsAdmin: true}).Find(&admins)
allAdmins = &admins
}

return *allAdmins
// TODO add cache and flush cache when admin changed
var admins []entity.User
dao.DB().Where(&entity.User{IsAdmin: true}).Find(&admins)
return admins
}

func (dao *Dao) GetAllAdminIDs() []uint {
Expand Down
43 changes: 42 additions & 1 deletion internal/dao/query_find_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package dao_test
import (
"testing"

"github.com/ArtalkJS/Artalk/internal/entity"
"github.com/ArtalkJS/Artalk/test"
"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -203,7 +204,47 @@ func TestGetAllAdmins(t *testing.T) {
defer app.Cleanup()

allAdmins := app.Dao().GetAllAdmins()
assert.GreaterOrEqual(t, len(allAdmins), 1)
assert.GreaterOrEqual(t, len(allAdmins), 1, "GetAllAdmins() not works")

t.Run("Test modify and get admins", func(t *testing.T) {
getContainsUser := func(userID uint) bool {
for _, a := range app.Dao().GetAllAdmins() {
if a.ID == userID {
return true
}
}
return false
}

// create
var adminID uint = 0
admin := entity.User{
Name: "TestAdmin",
Email: "admin@test.com",
IsAdmin: true,
}
app.Dao().CreateUser(&admin)
adminID = admin.ID
assert.NotZero(t, adminID, "user create failed")

assert.Equal(t, true, getContainsUser(adminID), "admin not found after create")

// update
admin.IsAdmin = false
app.Dao().UpdateUser(&admin)
assert.Equal(t, false, getContainsUser(adminID), "admin still exists after update")

// re-update
admin.IsAdmin = true
app.Dao().UpdateUser(&admin)
assert.Equal(t, true, getContainsUser(adminID), "admin not found after re-update to admin")

// delete
app.Dao().DelUser(&admin)

// not contains admin
assert.Equal(t, false, getContainsUser(adminID), "admin still exists after delete")
})
}

func TestIsAdminUser(t *testing.T) {
Expand Down

0 comments on commit 9dacd09

Please sign in to comment.