aboutsummaryrefslogtreecommitdiff
path: root/repository/sessionRepository.go
blob: d5f399abd2a348894248cb9add5cd470685a7f69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package repository

import (
	"encoding/json"
	"web/kv"
	"web/model"
)

type sessionRepository struct {
	db *kv.Database
}

func NewSessionRepository(db *kv.Database) *sessionRepository {
	return &sessionRepository{
		db: db,
	}
}

func (repo *sessionRepository) Add(s model.Session) (err error) {
	data, err := json.Marshal(s)
	if err != nil {
		return
	}
	err = repo.db.Set(s.ID, data)
	return
}

func (repo *sessionRepository) Update(id string, accessToken string) (err error) {
	data, err := repo.db.Get(id)
	if err != nil {
		return
	}

	var s model.Session
	err = json.Unmarshal(data, &s)
	if err != nil {
		return
	}

	s.AccessToken = accessToken

	data, err = json.Marshal(s)
	if err != nil {
		return
	}

	return repo.db.Set(id, data)
}

func (repo *sessionRepository) Get(id string) (s model.Session, err error) {
	data, err := repo.db.Get(id)
	if err != nil {
		err = model.ErrSessionNotFound
		return
	}

	err = json.Unmarshal(data, &s)
	if err != nil {
		return
	}

	return
}