1// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
2// See LICENSE.txt for license information.
3
4package localcachelayer
5
6import (
7	"bytes"
8
9	"github.com/mattermost/mattermost-server/v6/model"
10	"github.com/mattermost/mattermost-server/v6/store"
11)
12
13type LocalCacheReactionStore struct {
14	store.ReactionStore
15	rootStore *LocalCacheStore
16}
17
18func (s *LocalCacheReactionStore) handleClusterInvalidateReaction(msg *model.ClusterMessage) {
19	if bytes.Equal(msg.Data, clearCacheMessageData) {
20		s.rootStore.reactionCache.Purge()
21	} else {
22		s.rootStore.reactionCache.Remove(string(msg.Data))
23	}
24}
25
26func (s LocalCacheReactionStore) Save(reaction *model.Reaction) (*model.Reaction, error) {
27	defer s.rootStore.doInvalidateCacheCluster(s.rootStore.reactionCache, reaction.PostId)
28	return s.ReactionStore.Save(reaction)
29}
30
31func (s LocalCacheReactionStore) Delete(reaction *model.Reaction) (*model.Reaction, error) {
32	defer s.rootStore.doInvalidateCacheCluster(s.rootStore.reactionCache, reaction.PostId)
33	return s.ReactionStore.Delete(reaction)
34}
35
36func (s LocalCacheReactionStore) GetForPost(postId string, allowFromCache bool) ([]*model.Reaction, error) {
37	if !allowFromCache {
38		return s.ReactionStore.GetForPost(postId, false)
39	}
40
41	var reaction []*model.Reaction
42	if err := s.rootStore.doStandardReadCache(s.rootStore.reactionCache, postId, &reaction); err == nil {
43		return reaction, nil
44	}
45
46	reaction, err := s.ReactionStore.GetForPost(postId, false)
47	if err != nil {
48		return nil, err
49	}
50
51	s.rootStore.doStandardAddToCache(s.rootStore.reactionCache, postId, reaction)
52
53	return reaction, nil
54}
55
56func (s LocalCacheReactionStore) DeleteAllWithEmojiName(emojiName string) error {
57	// This could be improved. Right now we just clear the whole
58	// cache because we don't have a way find what post Ids have this emoji name.
59	defer s.rootStore.doClearCacheCluster(s.rootStore.reactionCache)
60	return s.ReactionStore.DeleteAllWithEmojiName(emojiName)
61}
62