forked from netlify/gotrue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
instance.go
84 lines (69 loc) · 2.33 KB
/
instance.go
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package models
import (
"database/sql"
"time"
"github.com/markbates/pop"
"github.com/netlify/gotrue/conf"
"github.com/netlify/gotrue/storage"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
)
const baseConfigKey = ""
type Instance struct {
ID uuid.UUID `json:"id" db:"id"`
// Netlify UUID
UUID uuid.UUID `json:"uuid,omitempty" db:"uuid"`
BaseConfig *conf.Configuration `json:"config" db:"raw_base_config"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
// Config loads the the base configuration values with defaults.
func (i *Instance) Config() (*conf.Configuration, error) {
if i.BaseConfig == nil {
return nil, errors.New("no configuration data available")
}
baseConf := &conf.Configuration{}
*baseConf = *i.BaseConfig
baseConf.ApplyDefaults()
return baseConf, nil
}
// UpdateConfig updates the base config
func (i *Instance) UpdateConfig(tx *storage.Connection, config *conf.Configuration) error {
i.BaseConfig = config
return tx.UpdateOnly(i, "raw_base_config")
}
// GetInstance finds an instance by ID
func GetInstance(tx *storage.Connection, instanceID uuid.UUID) (*Instance, error) {
instance := Instance{}
if err := tx.Find(&instance, instanceID); err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, InstanceNotFoundError{}
}
return nil, errors.Wrap(err, "error finding instance")
}
return &instance, nil
}
func GetInstanceByUUID(tx *storage.Connection, uuid uuid.UUID) (*Instance, error) {
instance := Instance{}
if err := tx.Where("uuid = ?", uuid).First(&instance); err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, InstanceNotFoundError{}
}
return nil, errors.Wrap(err, "error finding instance")
}
return &instance, nil
}
func DeleteInstance(conn *storage.Connection, instance *Instance) error {
return conn.Transaction(func(tx *storage.Connection) error {
delModels := map[string]*pop.Model{
"user": &pop.Model{Value: User{}},
"refresh token": &pop.Model{Value: RefreshToken{}},
}
for name, dm := range delModels {
if err := tx.RawQuery("DELETE FROM "+dm.TableName()+" WHERE instance_id = ?", instance.ID).Exec(); err != nil {
return errors.Wrapf(err, "Error deleting %s records", name)
}
}
return errors.Wrap(tx.Destroy(instance), "Error deleting instance record")
})
}