优化多租户逻辑

This commit is contained in:
COOL 2025-02-25 14:02:49 +08:00
parent 74a58f51e7
commit 32a0a6f73f

View File

@ -15,9 +15,11 @@ import {
Config, Config,
IMidwayApplication, IMidwayApplication,
IMidwayContext, IMidwayContext,
Init,
Inject, Inject,
} from '@midwayjs/core'; } from '@midwayjs/core';
import { Utils } from '../../../comm/utils'; import { Utils } from '../../../comm/utils';
import { CoolUrlTagData, TagTypes } from '@cool-midway/core';
/** /**
* *
@ -45,6 +47,9 @@ export class TenantSubscriber implements EntitySubscriberInterface<any> {
@Inject() @Inject()
ctx: IMidwayContext; ctx: IMidwayContext;
@Inject()
coolUrlTagData: CoolUrlTagData;
@Config('cool.tenant') @Config('cool.tenant')
tenant: { tenant: {
// 是否开启多租户 // 是否开启多租户
@ -67,6 +72,28 @@ export class TenantSubscriber implements EntitySubscriberInterface<any> {
@Inject() @Inject()
utils: Utils; utils: Utils;
/**
* url
*/
getAllIgnoreUrls() {
const adminIgnoreUrls = this.coolUrlTagData.byKey(
TagTypes.IGNORE_TOKEN,
'admin'
);
const appIgnoreUrls = this.coolUrlTagData.byKey(
TagTypes.IGNORE_TOKEN,
'app'
);
this.ignoreUrls = [
...this.ignoreUrls,
...adminIgnoreUrls,
...appIgnoreUrls,
];
// 去重
this.ignoreUrls = _.uniq(this.ignoreUrls);
return this.ignoreUrls;
}
/** /**
* *
*/ */
@ -112,7 +139,9 @@ export class TenantSubscriber implements EntitySubscriberInterface<any> {
return undefined; return undefined;
} }
// 忽略系统接口 // 忽略系统接口
if (this.ignoreUrls.some(pattern => this.utils.matchUrl(pattern, url))) { if (
this.getAllIgnoreUrls().some(pattern => this.utils.matchUrl(pattern, url))
) {
return undefined; return undefined;
} }
if (_.startsWith(url, '/admin/')) { if (_.startsWith(url, '/admin/')) {
@ -134,9 +163,11 @@ export class TenantSubscriber implements EntitySubscriberInterface<any> {
if (!this.tenant.enable) return; if (!this.tenant.enable) return;
const tenantId = this.getTenantId(); const tenantId = this.getTenantId();
if (tenantId) { if (tenantId) {
queryBuilder.where(`${queryBuilder.alias}.tenantId = :tenantId`, { queryBuilder.where(
tenantId, `${
}); queryBuilder.alias ? queryBuilder.alias + '.' : ''
}tenantId = ${tenantId}`
);
} }
} }
@ -161,7 +192,7 @@ export class TenantSubscriber implements EntitySubscriberInterface<any> {
const tenantId = await this.getTenantId(); const tenantId = await this.getTenantId();
if (tenantId) { if (tenantId) {
queryBuilder.set({ tenantId }); queryBuilder.set({ tenantId });
queryBuilder.where('tenantId = :tenantId', { tenantId }); queryBuilder.where(`tenantId = ${tenantId}`);
} }
} }
@ -173,7 +204,7 @@ export class TenantSubscriber implements EntitySubscriberInterface<any> {
if (!this.tenant.enable) return; if (!this.tenant.enable) return;
const tenantId = await this.getTenantId(); const tenantId = await this.getTenantId();
if (tenantId) { if (tenantId) {
queryBuilder.where('tenantId = :tenantId', { tenantId }); queryBuilder.where(`tenantId = ${tenantId}`);
} }
} }
} }