-
Notifications
You must be signed in to change notification settings - Fork 264
/
multi-tenant.ts
52 lines (46 loc) · 1.19 KB
/
multi-tenant.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
51
52
/**
* This is the multi tenant module
* @module
*/
import { sqlsanitize } from "./internal";
import { AsyncLocalStorage } from "async_hooks";
const is_multi_tenant = true;
let connObj: any = null;
export const tenantNamespace = new AsyncLocalStorage();
/**
* set the connection object of the multi-tenant
* @param connObjPara
*/
export const init = (connObjPara: any): void => {
connObj = connObjPara;
};
/**
* Returns true if platform runs multi tenant mode
* @returns {boolean}
*/
export const is_it_multi_tenant = (): boolean => is_multi_tenant;
/**
* @returns {void}
*/
export const enable_multi_tenant = (): void => {};
/**
* Run function with tenant
* @param {object} tenant
* @param {function} f
* @returns {object}
*/
export const runWithTenant = <Type>(
tenant: string,
f: () => Promise<Type>
): Promise<Type> => {
if (!is_multi_tenant) return f();
else return tenantNamespace.run(sqlsanitize(tenant).toLowerCase(), f);
};
/**
* Get tenant schema name
*/
export const getTenantSchema = (): string => {
if (!connObj) throw new Error("The connection object is not initialized");
const storeVal = tenantNamespace.getStore();
return storeVal || connObj.default_schema;
};