Repository navigation
Expand file tree
/
Copy pathroleDataService.ts
More file actions
296 lines (262 loc) · 8.33 KB
/
Copy pathroleDataService.ts
File metadata and controls
296 lines (262 loc) · 8.33 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/**
* 统一数据查询服务
* 提供松耦合的数据访问接口,支持精确到JSON叶节点的查询
* 内置内存缓存,同一查询在组件重新挂载时不会重复发起 IPC 调用
*/
import { invoke } from '@tauri-apps/api/core';
import { logDebug, logInfo, logError } from './logger';
import { trackStartupTask } from './startupProgress';
/**
* 查询结果类型
* key: 请求的路径
* value: 对应的值(如果路径不存在则为 null)
*/
export type QueryResult = Record<string, any>;
const queryCache = new Map<string, Promise<QueryResult | null>>();
function cacheKey(roleId: string, apiName: string, paths: string[]): string {
return `${roleId}|${apiName}|${paths.join(",")}`;
}
/**
* 角色数据服务
*/
export class RoleDataService {
/**
* 清除指定查询的缓存
*/
clearCache(roleId: string, apiName: string, paths: string[] = []): void {
queryCache.delete(cacheKey(roleId, apiName, paths));
}
/**
* 清除所有缓存
*/
clearAllCache(): void {
queryCache.clear();
}
/**
* 统一数据查询接口
*
* @param roleId - 角色ID
* @param apiName - API名称(如 'char_detail')
* @param paths - 路径列表,每个路径精确到JSON叶节点
* - 空数组表示返回完整数据
* - 例如: ['base.name', 'chars.0.charData.id', 'chars.0.charData.avatarSqUrl']
* @returns 查询结果,key为路径,value为对应的值
*
* @example
* // 获取完整数据
* const fullData = await queryData('role_123', 'char_detail', []);
*
* // 获取特定字段
* const result = await queryData('role_123', 'char_detail', [
* 'base.name',
* 'base.level',
* 'chars.0.charData.id',
* 'chars.0.charData.name'
* ]);
* // 返回: { 'base.name': 'Player1', 'base.level': 50, 'chars.0.charData.id': 'char_001', ... }
*/
async queryData(
roleId: string,
apiName: string,
paths: string[] = []
): Promise<QueryResult | null> {
const key = cacheKey(roleId, apiName, paths);
const pending = queryCache.get(key);
if (pending) {
logDebug(`[RoleDataService] Cache hit: ${key}`);
return pending;
}
logInfo(
`[RoleDataService] Querying: roleId=${roleId}, apiName=${apiName}, paths=${paths.length}`
);
const promise = (async (): Promise<QueryResult | null> => {
try {
const result = await invoke<Record<string, any>>('query_role_data', {
roleId,
apiName,
paths,
});
logDebug(`[RoleDataService] Query successful, received ${Object.keys(result).length} paths`);
return result;
} catch (error) {
queryCache.delete(key);
logError(`[RoleDataService] Query failed:`, error);
return null;
}
})();
queryCache.set(key, promise);
return trackStartupTask(promise);
}
/**
* 获取完整的角色详情数据
*
* @param roleId - 角色ID
* @returns 完整的角色详情JSON对象
*/
async getFullCharDetail(roleId: string): Promise<any | null> {
const result = await this.queryData(roleId, 'char_detail', []);
if (result && result.__full__) {
return result.__full__;
}
return null;
}
/**
* 获取角色基础信息
*
* @param roleId - 角色ID
* @returns 基础信息对象 { name, level, serverName, ... }
*/
async getBaseInfo(roleId: string): Promise<any | null> {
const result = await this.queryData(roleId, 'char_detail', ['base']);
if (result && result.base) {
return result.base;
}
return null;
}
/**
* 获取角色名称
*
* @param roleId - 角色ID
* @returns 角色名称
*/
async getRoleName(roleId: string): Promise<string | null> {
const result = await this.queryData(roleId, 'char_detail', ['base.name']);
if (result && result['base.name']) {
return result['base.name'];
}
return null;
}
/**
* 获取指定索引的干员数据
*
* @param roleId - 角色ID
* @param charIndex - 干员在数组中的索引
* @returns 干员数据对象
*/
async getCharacter(roleId: string, charIndex: number): Promise<any | null> {
const result = await this.queryData(roleId, 'char_detail', [`chars.${charIndex}`]);
if (result && result[`chars.${charIndex}`]) {
return result[`chars.${charIndex}`];
}
return null;
}
/**
* 获取所有干员的ID列表
*
* @param roleId - 角色ID
* @returns 干员ID数组
*/
async getAllCharIds(roleId: string): Promise<string[]> {
const result = await this.queryData(roleId, 'char_detail', ['chars']);
if (result && result.chars && Array.isArray(result.chars)) {
return result.chars
.map((char: any) => char.charData?.id)
.filter((id: string) => id !== undefined && id !== null);
}
return [];
}
/**
* 批量获取多个路径的数据
*
* @param roleId - 角色ID
* @param paths - 路径列表
* @returns 查询结果
*/
async batchQuery(roleId: string, paths: string[]): Promise<QueryResult | null> {
return this.queryData(roleId, 'char_detail', paths);
}
// ====== Wiki 相关方法 ======
/**
* 获取单个角色的 Wiki 详情(char_wiki_detail)
*
* @param roleId - 角色ID
* @param itemId - Wiki 物品 ID
* @returns Wiki 详情数据(含 coverUrl)
*/
async getWikiItemDetail(roleId: string, itemId: string): Promise<any | null> {
const result = await this.queryData(roleId, 'char_wiki_detail', [itemId]);
if (!result) return null;
const raw = result[itemId];
if (!raw) return null;
if (raw.data?.item) return raw.data.item;
if (raw.data?.brief) return raw.data;
if (raw.item) return raw.item;
return raw;
}
/**
* 获取物品目录(item catalog),用于将物品 ID 映射为名称和封面图
*
* @param roleId - 角色ID(需要鉴权)
* @returns 物品 ID → { name, cover } 的映射
*/
async getItemCatalog(
roleId: string,
): Promise<Map<string, { name: string; cover: string }> | null> {
const result = await this.queryData(roleId, 'wiki_catalog', []);
if (!result || !result.__full__) {
console.log('[RoleDataService] getItemCatalog: no result or __full__');
return null;
}
const raw = result.__full__;
const catalogArr = raw.data?.catalog;
if (!Array.isArray(catalogArr)) {
console.log('[RoleDataService] getItemCatalog: catalogArr is not array, raw.data:', raw.data);
return null;
}
const map = new Map<string, { name: string; cover: string }>();
let itemCount = 0;
let withCover = 0;
for (const entry of catalogArr) {
const subs = entry.typeSub;
if (!Array.isArray(subs)) continue;
for (const sub of subs) {
const items = sub.items;
if (!Array.isArray(items)) continue;
for (const item of items) {
if (item.itemId && item.name) {
const cover = item.brief?.cover || '';
if (cover) withCover++;
itemCount++;
map.set(item.itemId, {
name: item.name,
cover,
});
// 打印前3个item的原始结构
if (itemCount <= 3) {
console.log(`[RoleDataService] catalog item #${itemCount} raw:`, JSON.stringify(item).substring(0, 500));
}
}
}
}
}
console.log(`[RoleDataService] getItemCatalog: ${itemCount} items, ${withCover} with cover`);
return map;
}
/**
* 批量获取多个物品的 Wiki 详情
*
* @param roleId - 角色ID
* @param itemIds - 物品 ID 数组
* @returns itemId → 详情数据的映射
*/
async getWikiItemDetails(
roleId: string,
itemIds: string[],
): Promise<Record<string, any>> {
if (itemIds.length === 0) return {};
const result = await this.queryData(roleId, 'char_wiki_detail', itemIds);
if (!result) return {};
const details: Record<string, any> = {};
for (const itemId of itemIds) {
const raw = result[itemId];
if (!raw) continue;
if (raw.data?.item) details[itemId] = raw.data.item;
else if (raw.data?.brief) details[itemId] = raw.data;
else if (raw.item) details[itemId] = raw.item;
else details[itemId] = raw;
}
return details;
}
}
// 导出单例
export const roleDataService = new RoleDataService();