github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/common/menu_store.go (about)

     1  package common
     2  
     3  import (
     4  	"database/sql"
     5  	"strconv"
     6  	"sync/atomic"
     7  
     8  	qgen "github.com/Azareal/Gosora/query_gen"
     9  )
    10  
    11  var Menus *DefaultMenuStore
    12  
    13  type DefaultMenuStore struct {
    14  	menus     map[int]*atomic.Value
    15  	itemStore *DefaultMenuItemStore
    16  }
    17  
    18  func NewDefaultMenuStore() *DefaultMenuStore {
    19  	return &DefaultMenuStore{
    20  		make(map[int]*atomic.Value),
    21  		NewDefaultMenuItemStore(),
    22  	}
    23  }
    24  
    25  // TODO: Add actual support for multiple menus
    26  func (s *DefaultMenuStore) GetAllMap() (out map[int]*MenuListHolder) {
    27  	out = make(map[int]*MenuListHolder)
    28  	for mid, atom := range s.menus {
    29  		out[mid] = atom.Load().(*MenuListHolder)
    30  	}
    31  	return out
    32  }
    33  
    34  func (s *DefaultMenuStore) Get(mid int) (*MenuListHolder, error) {
    35  	aStore, ok := s.menus[mid]
    36  	if ok {
    37  		return aStore.Load().(*MenuListHolder), nil
    38  	}
    39  	return nil, ErrNoRows
    40  }
    41  
    42  func (s *DefaultMenuStore) Items(mid int) (mlist MenuItemList, err error) {
    43  	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 {
    44  		i := MenuItem{MenuID: mid}
    45  		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)
    46  		if err != nil {
    47  			return err
    48  		}
    49  		s.itemStore.Add(i)
    50  		mlist = append(mlist, i)
    51  		return nil
    52  	})
    53  	return mlist, err
    54  }
    55  
    56  func (s *DefaultMenuStore) Load(mid int) error {
    57  	mlist, err := s.Items(mid)
    58  	if err != nil {
    59  		return err
    60  	}
    61  	hold := &MenuListHolder{mid, mlist, make(map[int]menuTmpl)}
    62  	err = hold.Preparse()
    63  	if err != nil {
    64  		return err
    65  	}
    66  
    67  	aStore := &atomic.Value{}
    68  	aStore.Store(hold)
    69  	s.menus[mid] = aStore
    70  	return nil
    71  }
    72  
    73  func (s *DefaultMenuStore) ItemStore() *DefaultMenuItemStore {
    74  	return s.itemStore
    75  }