-
Notifications
You must be signed in to change notification settings - Fork 577
/
tenantManager.ts
50 lines (41 loc) · 1.24 KB
/
tenantManager.ts
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
import {
ApplicationContext,
ASYNC_CONTEXT_KEY,
ASYNC_CONTEXT_MANAGER_KEY,
AsyncContextManager,
IMidwayContainer,
IMidwayContext,
MidwayEmptyValueError,
Singleton,
} from '@midwayjs/core';
const CURRENT_TENANT_MANAGER_KEY = 'tenant:current_manager_tenant_key';
@Singleton()
export class TenantManager {
@ApplicationContext()
applicationContext: IMidwayContainer;
async getCurrentTenant<T = any>(): Promise<T> {
const contextManager: AsyncContextManager = this.applicationContext.get(
ASYNC_CONTEXT_MANAGER_KEY
);
const ctx = contextManager
.active()
.getValue(ASYNC_CONTEXT_KEY) as IMidwayContext;
if (ctx) {
return ctx.getAttr(CURRENT_TENANT_MANAGER_KEY);
}
}
async setCurrentTenant<T = any>(currentTenant: T): Promise<void> {
const contextManager: AsyncContextManager = this.applicationContext.get(
ASYNC_CONTEXT_MANAGER_KEY
);
const activeContext = contextManager.active();
const requestContext = activeContext.getValue(
ASYNC_CONTEXT_KEY
) as IMidwayContext;
if (requestContext) {
requestContext.setAttr(CURRENT_TENANT_MANAGER_KEY, currentTenant);
} else {
throw new MidwayEmptyValueError('Current Async Context is Empty');
}
}
}