mirror of
https://github.com/mattermost/mattermost.git
synced 2025-02-25 18:55:24 -06:00
* move kv helpers to helpers_kv*.go * change KVGetJSON return signature Return a boolean and an error, to clearly indicate if no value was found and thus no value unmarshalled into the target interface. Also fix an issue with CompareAndSet to allow an oldValue of nil (i.e. expected to be unset). * add missing license * tweak documentation * document KVSetWithExpiryJSON minimum version
71 lines
1.8 KiB
Go
71 lines
1.8 KiB
Go
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
|
// See LICENSE.txt for license information.
|
|
|
|
package plugin
|
|
|
|
import (
|
|
"encoding/json"
|
|
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
// KVGetJSON is a wrapper around KVGet to simplify reading a JSON object from the key value store.
|
|
func (p *HelpersImpl) KVGetJSON(key string, value interface{}) (bool, error) {
|
|
data, appErr := p.API.KVGet(key)
|
|
if appErr != nil {
|
|
return false, appErr
|
|
}
|
|
if data == nil {
|
|
return false, nil
|
|
}
|
|
|
|
err := json.Unmarshal(data, value)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
// KVSetJSON is a wrapper around KVSet to simplify writing a JSON object to the key value store.
|
|
func (p *HelpersImpl) KVSetJSON(key string, value interface{}) error {
|
|
data, err := json.Marshal(value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return p.API.KVSet(key, data)
|
|
}
|
|
|
|
// KVCompareAndSetJSON is a wrapper around KVCompareAndSet to simplify atomically writing a JSON object to the key value store.
|
|
func (p *HelpersImpl) KVCompareAndSetJSON(key string, oldValue interface{}, newValue interface{}) (bool, error) {
|
|
var oldData, newData []byte
|
|
var err error
|
|
|
|
if oldValue != nil {
|
|
oldData, err = json.Marshal(oldValue)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "unable to marshal old value")
|
|
}
|
|
}
|
|
|
|
if newValue != nil {
|
|
newData, err = json.Marshal(newValue)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "unable to marshal new value")
|
|
}
|
|
}
|
|
|
|
return p.API.KVCompareAndSet(key, oldData, newData)
|
|
}
|
|
|
|
// KVSetWithExpiryJSON is a wrapper around KVSetWithExpiry to simplify atomically writing a JSON object with expiry to the key value store.
|
|
func (p *HelpersImpl) KVSetWithExpiryJSON(key string, value interface{}, expireInSeconds int64) error {
|
|
data, err := json.Marshal(value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return p.API.KVSetWithExpiry(key, data, expireInSeconds)
|
|
}
|