gosora/common/menu_store.go

76 lines
2.0 KiB
Go
Raw Normal View History

package common
import (
2022-02-21 03:53:13 +00:00
"database/sql"
"strconv"
"sync/atomic"
2022-02-21 03:53:13 +00:00
qgen "git.tuxpa.in/a/gosora/query_gen"
)
var Menus *DefaultMenuStore
type DefaultMenuStore struct {
2022-02-21 03:32:53 +00:00
menus map[int]*atomic.Value
itemStore *DefaultMenuItemStore
}
func NewDefaultMenuStore() *DefaultMenuStore {
2022-02-21 03:32:53 +00:00
return &DefaultMenuStore{
make(map[int]*atomic.Value),
NewDefaultMenuItemStore(),
}
}
// TODO: Add actual support for multiple menus
func (s *DefaultMenuStore) GetAllMap() (out map[int]*MenuListHolder) {
2022-02-21 03:32:53 +00:00
out = make(map[int]*MenuListHolder)
for mid, atom := range s.menus {
out[mid] = atom.Load().(*MenuListHolder)
}
return out
}
func (s *DefaultMenuStore) Get(mid int) (*MenuListHolder, error) {
2022-02-21 03:32:53 +00:00
aStore, ok := s.menus[mid]
if ok {
return aStore.Load().(*MenuListHolder), nil
}
return nil, ErrNoRows
}
func (s *DefaultMenuStore) Items(mid int) (mlist MenuItemList, err error) {
2022-02-21 03:32:53 +00:00
err = qgen.NewAcc().Select("menu_items").Columns("miid,name,htmlID,cssClass,position,path,aria,tooltip,order,tmplName,guestOnly,memberOnly,staffOnly,adminOnly").Where("mid=" + strconv.Itoa(mid)).Orderby("order ASC").Each(func(rows *sql.Rows) error {
i := MenuItem{MenuID: mid}
err := rows.Scan(&i.ID, &i.Name, &i.HTMLID, &i.CSSClass, &i.Position, &i.Path, &i.Aria, &i.Tooltip, &i.Order, &i.TmplName, &i.GuestOnly, &i.MemberOnly, &i.SuperModOnly, &i.AdminOnly)
if err != nil {
return err
}
s.itemStore.Add(i)
mlist = append(mlist, i)
return nil
})
return mlist, err
}
func (s *DefaultMenuStore) Load(mid int) error {
2022-02-21 03:32:53 +00:00
mlist, err := s.Items(mid)
if err != nil {
return err
}
hold := &MenuListHolder{mid, mlist, make(map[int]menuTmpl)}
err = hold.Preparse()
if err != nil {
return err
}
2022-02-21 03:32:53 +00:00
aStore := &atomic.Value{}
aStore.Store(hold)
s.menus[mid] = aStore
return nil
}
func (s *DefaultMenuStore) ItemStore() *DefaultMenuItemStore {
2022-02-21 03:32:53 +00:00
return s.itemStore
}