-
Notifications
You must be signed in to change notification settings - Fork 44
/
multi_tenancy_conn_str_resolver.go
59 lines (51 loc) · 1.28 KB
/
multi_tenancy_conn_str_resolver.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
package saas
import (
"context"
"github.com/go-saas/saas/data"
)
type MultiTenancyConnStrResolver struct {
//use creator to prevent circular dependency
ts TenantStore
fallback data.ConnStrResolver
}
var _ data.ConnStrResolver = (*MultiTenancyConnStrResolver)(nil)
// NewMultiTenancyConnStrResolver from tenant
func NewMultiTenancyConnStrResolver(ts TenantStore, fallback data.ConnStrResolver) *MultiTenancyConnStrResolver {
return &MultiTenancyConnStrResolver{
ts: ts,
fallback: fallback,
}
}
func (m *MultiTenancyConnStrResolver) Resolve(ctx context.Context, key string) (string, error) {
tenantInfo, _ := FromCurrentTenant(ctx)
id := tenantInfo.GetId()
if len(id) == 0 {
//skip query tenant store
return m.fallback.Resolve(ctx, key)
}
var tenantConfig *TenantConfig
//read from cache
if tenant, ok := FromTenantConfigContext(ctx, id); ok {
tenantConfig = tenant
} else {
tenant, err := m.ts.GetByNameOrId(ctx, id)
if err != nil {
return "", err
}
tenantConfig = tenant
}
if tenantConfig.Conn == nil {
//not found
return m.fallback.Resolve(ctx, key)
}
//get key
ret, err := tenantConfig.Conn.Resolve(ctx, key)
if err != nil {
return "", err
}
if ret != "" {
return ret, nil
}
//still not found
return m.fallback.Resolve(ctx, key)
}