github.com/decred/politeia@v1.4.0/politeiawww/legacy/user/localdb/encoding.go (about)

     1  package localdb
     2  
     3  import (
     4  	"encoding/json"
     5  	"path/filepath"
     6  	"time"
     7  
     8  	"github.com/syndtr/goleveldb/leveldb"
     9  )
    10  
    11  // EncodeVersion encodes Version into a JSON byte slice.
    12  func EncodeVersion(version Version) ([]byte, error) {
    13  	b, err := json.Marshal(version)
    14  	if err != nil {
    15  		return nil, err
    16  	}
    17  
    18  	return b, nil
    19  }
    20  
    21  // DecodeVersion decodes a JSON byte slice into a Version.
    22  func DecodeVersion(payload []byte) (*Version, error) {
    23  	var version Version
    24  
    25  	err := json.Unmarshal(payload, &version)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  
    30  	return &version, nil
    31  }
    32  
    33  // openUserDB opens the user database and writes out the version record if
    34  // needed.
    35  func (l *localdb) openUserDB(path string) error {
    36  	// open database
    37  	var err error
    38  	l.userdb, err = leveldb.OpenFile(filepath.Join(l.root, UserdbPath), nil)
    39  	if err != nil {
    40  		return err
    41  	}
    42  
    43  	// See if we need to write a version record
    44  	exists, err := l.userdb.Has([]byte(UserVersionKey), nil)
    45  	if err != nil || exists {
    46  		return err
    47  	}
    48  
    49  	// Write version record
    50  	v, err := EncodeVersion(Version{
    51  		Version: UserVersion,
    52  		Time:    time.Now().Unix(),
    53  	})
    54  	if err != nil {
    55  		return err
    56  	}
    57  	return l.userdb.Put([]byte(UserVersionKey), v, nil)
    58  }