aboutsummaryrefslogtreecommitdiff
path: root/repository/sessionRepository.go
blob: 2a88b40cbf29c81b390c5c2833a6d1d18fa5764b (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
package repository

import (
	"database/sql"

	"web/model"
)

type sessionRepository struct {
	db *sql.DB
}

func NewSessionRepository(db *sql.DB) (*sessionRepository, error) {
	_, err := db.Exec(`CREATE TABLE IF NOT EXISTS session 
		(id varchar, instance_url varchar, access_token varchar)`,
	)
	if err != nil {
		return nil, err
	}

	return &sessionRepository{
		db: db,
	}, nil
}

func (repo *sessionRepository) Add(s model.Session) (err error) {
	_, err = repo.db.Exec("INSERT INTO session VALUES (?, ?, ?)", s.ID, s.InstanceURL, s.AccessToken)
	return
}

func (repo *sessionRepository) Update(sessionID string, accessToken string) (err error) {
	_, err = repo.db.Exec("UPDATE session SET access_token = ? where id = ?", accessToken, sessionID)
	return
}

func (repo *sessionRepository) Get(id string) (s model.Session, err error) {
	rows, err := repo.db.Query("SELECT * FROM session WHERE id = ?", id)
	if err != nil {
		return
	}
	defer rows.Close()

	if !rows.Next() {
		err = model.ErrSessionNotFound
		return
	}

	err = rows.Scan(&s.ID, &s.InstanceURL, &s.AccessToken)
	if err != nil {
		return
	}

	return
}