-
Notifications
You must be signed in to change notification settings - Fork 44
/
tenant_config_provider.go
46 lines (39 loc) · 1.18 KB
/
tenant_config_provider.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
package saas
import "context"
// TenantConfigProvider resolve tenant config from current context
type TenantConfigProvider interface {
// Get tenant config
Get(ctx context.Context) (TenantConfig, context.Context, error)
}
type DefaultTenantConfigProvider struct {
tr TenantResolver
ts TenantStore
}
func NewDefaultTenantConfigProvider(tr TenantResolver, ts TenantStore) TenantConfigProvider {
return &DefaultTenantConfigProvider{
tr: tr,
ts: ts,
}
}
// Get read from context FromTenantConfigContext first, fallback with TenantStore and return new context with cached value
func (d *DefaultTenantConfigProvider) Get(ctx context.Context) (TenantConfig, context.Context, error) {
rr, ctx, err := d.tr.Resolve(ctx)
if err != nil {
return TenantConfig{}, ctx, err
}
if rr.TenantIdOrName != "" {
//tenant side
//read from cache
if cfg, ok := FromTenantConfigContext(ctx, rr.TenantIdOrName); ok {
return *cfg, ctx, nil
}
//get config from tenant store
cfg, err := d.ts.GetByNameOrId(ctx, rr.TenantIdOrName)
if err != nil {
return TenantConfig{}, ctx, err
}
return *cfg, NewTenantConfigContext(ctx, cfg.ID, cfg), nil
}
// host side
return TenantConfig{}, ctx, nil
}