@blueking/bk-user-display-name
Version:
多租户环境用于显示用户名称的组件
147 lines (146 loc) • 5.59 kB
JavaScript
;
// declare global {
// interface Window {
// BkUserDisplayName: typeof BkUserDisplayName;
// }
// }
Object.defineProperty(exports, "__esModule", { value: true });
class BkUserDisplayName extends HTMLElement {
// 配置
static configure(config) {
if (config.apiBaseUrl) {
BkUserDisplayName.apiBaseUrl = config.apiBaseUrl;
}
if (config.tenantId) {
BkUserDisplayName.tenantId = config.tenantId;
}
if (typeof config.cacheDuration === 'number') {
BkUserDisplayName.cacheDuration = config.cacheDuration;
}
if (config.emptyText !== undefined) {
BkUserDisplayName.emptyText = config.emptyText;
}
}
constructor() {
// 必须首先调用 super 方法
super();
}
async fetchUser(id) {
// 检查是否有进行中的相同请求
const pendingRequest = BkUserDisplayName.pendingRequests.get(id);
if (pendingRequest) {
// 如果有,直接返回该Promise
return pendingRequest;
}
// 添加fetch配置
const fetchConfig = {
credentials: 'include',
headers: {
'X-Bk-Tenant-Id': BkUserDisplayName.tenantId, // 添加 tenantId header
},
};
// 创建新的请求
const promise = fetch(`${BkUserDisplayName.apiBaseUrl}/api/v3/open-web/tenant/users/${id}/display_info/`, fetchConfig)
.then(response => response.json())
.finally(() => {
// 请求完成后,删除pending状态
BkUserDisplayName.pendingRequests.delete(id);
});
// 存储请求Promise
BkUserDisplayName.pendingRequests.set(id, promise);
return promise;
}
async fetchUsers(ids) {
// 添加fetch配置
const fetchConfig = {
credentials: 'include',
headers: {
'X-Bk-Tenant-Id': BkUserDisplayName.tenantId, // 添加 tenantId header
},
};
// 创建新的请求
const promise = fetch(`${BkUserDisplayName.apiBaseUrl}/api/v3/open-web/tenant/users/-/display_info/?bk_usernames=${ids.join(',')}`, fetchConfig)
.then(response => response.json());
return promise;
}
// 添加属性变化的回调方法
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'user-id' && oldValue !== newValue) {
this.updateDisplay();
}
}
async updateDisplay() {
const id = this.getAttribute('user-id');
if (!id) {
this.textContent = BkUserDisplayName.emptyText;
return;
}
this.textContent = '...';
this.textContent = await this.getDisplayName();
}
// 修改 connectedCallback 调用新方法
// async connectedCallback(): Promise<void> {
// console.log('connectedCallback');
// // this.updateDisplay();
// }
// 获取用户名称
async getDisplayName() {
var _a, _b;
const id = (_a = this.getAttribute('user-id')) === null || _a === void 0 ? void 0 : _a.trim();
if (!id)
return '';
// 支持传入多个用户 ID,用逗号分隔,兼容中文逗号和英文逗号,还有分号情况
const ids = id.split(/[,,;]/).map(id => id.trim()).filter(id => id);
try {
if (ids.length === 1) {
let userResponse;
const cached = BkUserDisplayName.userCache.get(id);
// 检查缓存是否存在且未过期
if (cached && Date.now() - cached.timestamp < BkUserDisplayName.cacheDuration) {
userResponse = cached.data;
}
else {
// 使用fetchUser方法获取单个数据
userResponse = await this.fetchUser(id);
// 存储数据和时间戳
BkUserDisplayName.userCache.set(id, {
data: userResponse,
timestamp: Date.now(),
});
}
return ((_b = userResponse.data) === null || _b === void 0 ? void 0 : _b.display_name) || id;
}
else {
const usersResponse = await this.fetchUsers(ids);
const userList = ids.map(id => {
var _a;
const user = (_a = usersResponse.data) === null || _a === void 0 ? void 0 : _a.find((user) => user.bk_username === id);
return (user === null || user === void 0 ? void 0 : user.display_name) || id;
});
return userList.join(',');
}
}
catch (error) {
console.error('DisplayName 获取用户数据失败:', error);
return id;
}
}
}
// 缓存
BkUserDisplayName.userCache = new Map();
// 缓存过期时间(毫秒)
BkUserDisplayName.cacheDuration = 5 * 60 * 1000; // 5分钟
// 存储进行中的请求
BkUserDisplayName.pendingRequests = new Map();
// 请求的 API 基础 URL
BkUserDisplayName.apiBaseUrl = '';
// 租户 ID
BkUserDisplayName.tenantId = '';
// 当输入为空时,显示的文本
BkUserDisplayName.emptyText = '--';
// 定义需要监听的属性
BkUserDisplayName.observedAttributes = ['user-id'];
customElements.define('bk-user-display-name', BkUserDisplayName);
// 导出 BkUserDisplayName 类
// window.BkUserDisplayName = BkUserDisplayName;
exports.default = BkUserDisplayName;