Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(cache): unable to change admin list after caching (#748) #750

Merged
merged 1 commit into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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: "[email protected]",
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