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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
|
import { useQuery } from '@tanstack/vue-query';
import { computed } from 'vue';
import api from '@/store/api';
import { useRedfishRoot, supportsExpandQuery } from './useRedfishRoot';
/**
* Redfish collection member reference
*/
export interface CollectionMember {
'@odata.id': string;
}
/**
* Redfish collection response
*/
export interface RedfishCollection<T = unknown> {
'@odata.id': string;
'@odata.type': string;
Name: string;
Members: T[];
'Members@odata.count': number;
}
/**
* OData Query Parameters for Redfish API
*/
export interface RedfishQueryParameters {
$expand?:
| string
| {
$levels?: number;
$noLinks?: boolean;
$expandAll?: boolean;
$links?: string;
};
$filter?: string;
$select?: string | string[];
$top?: number;
$skip?: number;
only?: boolean;
excerpt?: boolean;
}
/**
* Options for fetching a Redfish collection
*/
export interface FetchCollectionOptions {
expand?: boolean;
expandLevels?: number;
select?: string[];
filter?: string;
}
/**
* Builds a Redfish API URL with OData query parameters
*
* Handles proper encoding and formatting of OData directives:
* - $expand with nested options like .($levels=2)
* - $select with multiple properties
* - $filter, $top, $skip for pagination and filtering
* - Custom Redfish parameters like 'only' and 'excerpt'
*
* @param path - Base path (e.g., '/redfish/v1/Chassis')
* @param params - OData query parameters
* @returns Complete URL with query string
*
* @example
* buildQuery('/redfish/v1/Chassis', { $expand: '*' })
* // Returns: '/redfish/v1/Chassis?$expand=*'
*
* @example
* buildQuery('/redfish/v1/Systems', {
* $expand: { $levels: 2, $noLinks: true }
* })
* // Returns: '/redfish/v1/Systems?$expand=.($levels=2;$noLinks=true)'
*/
export function buildQuery(
path: string,
params?: RedfishQueryParameters,
): string {
if (!params) return path;
const pairs: string[] = [];
// Handle $expand parameter
if (params.$expand) {
if (typeof params.$expand === 'string') {
// Simple string expand (e.g., '*' or 'Members')
// Do not encode $ directives inside the value
pairs.push(`$expand=${params.$expand}`);
} else {
// Complex expand with options
const expandParts: string[] = [];
if (params.$expand.$levels !== undefined) {
expandParts.push(`$levels=${params.$expand.$levels}`);
}
if (params.$expand.$noLinks !== undefined) {
expandParts.push(`$noLinks=${params.$expand.$noLinks}`);
}
if (params.$expand.$expandAll !== undefined) {
expandParts.push(`$expandAll=${params.$expand.$expandAll}`);
}
if (params.$expand.$links !== undefined) {
expandParts.push(`$links=${params.$expand.$links}`);
}
// Build .(options) without encoding the $ directives
// Use ';' between options per OData specification
const opts = expandParts.join(';');
pairs.push(`$expand=.(${opts})`);
}
}
// Handle $filter parameter
if (params.$filter) {
pairs.push(`$filter=${encodeURIComponent(params.$filter)}`);
}
// Handle $select parameter
if (params.$select) {
const sel = Array.isArray(params.$select)
? params.$select.join(',')
: params.$select;
pairs.push(`$select=${encodeURIComponent(sel)}`);
}
// Handle $top parameter (pagination)
if (params.$top !== undefined) {
pairs.push(`$top=${encodeURIComponent(String(params.$top))}`);
}
// Handle $skip parameter (pagination)
if (params.$skip !== undefined) {
pairs.push(`$skip=${encodeURIComponent(String(params.$skip))}`);
}
// Handle 'only' parameter (Redfish-specific)
if (params.only) {
pairs.push('only=');
}
// Handle 'excerpt' parameter (Redfish-specific)
if (params.excerpt !== undefined) {
pairs.push(`excerpt=${encodeURIComponent(String(params.excerpt))}`);
}
const qs = pairs.join('&');
return qs ? `${path}?${qs}` : path;
}
/**
* Normalizes Redfish query parameters for cache stability
*
* Ensures consistent query keys by:
* - Sorting array values (like $select)
* - Freezing the result to prevent mutations
* - Handling undefined values consistently
*
* @param params - Query parameters to normalize
* @returns Normalized and frozen parameters, or undefined if input is undefined
*/
function normalizeRedfishQueryParameters(
params?: RedfishQueryParameters,
): Readonly<RedfishQueryParameters> | undefined {
if (!params) return undefined;
const normalizedSelect =
params.$select === undefined
? undefined
: Array.isArray(params.$select)
? [...params.$select].sort()
: params.$select;
const normalizedExpand =
params.$expand === undefined
? undefined
: typeof params.$expand === 'string'
? params.$expand
: {
$levels: params.$expand.$levels,
$noLinks: params.$expand.$noLinks,
$expandAll: params.$expand.$expandAll,
$links: params.$expand.$links,
};
return Object.freeze({
$expand: normalizedExpand,
$filter: params.$filter,
$select: normalizedSelect,
$top: params.$top,
$skip: params.$skip,
only: params.only,
excerpt: params.excerpt,
});
}
/**
* Fetches a Redfish collection with optional OData query parameters
* Gracefully falls back if BMC doesn't support OData features
*
* @param path - Collection path (e.g., '/redfish/v1/Chassis')
* @param options - Fetch options
* @param supportsExpand - Whether BMC supports $expand
* @returns Promise with collection data
*/
async function fetchCollection<T>(
path: string,
options: FetchCollectionOptions,
supportsExpand: boolean,
): Promise<T[]> {
const { expand, expandLevels = 1, select, filter } = options;
// Build query parameters using the reusable buildQuery function
const queryParams: RedfishQueryParameters = {};
if (expand && supportsExpand) {
queryParams.$expand = { $levels: expandLevels };
}
if (select && select.length > 0) {
queryParams.$select = select;
}
if (filter) {
queryParams.$filter = filter;
}
const url = buildQuery(path, queryParams);
try {
const { data } = await api.get<RedfishCollection<T>>(url);
if (expand && supportsExpand && data.Members) {
return data.Members;
}
if (data.Members && Array.isArray(data.Members)) {
const memberPromises = data.Members.map((member: CollectionMember) =>
api
.get<T>(member['@odata.id'])
.then((res: { data: T }) => res.data)
.catch((error: Object) => {
console.error(
`Error fetching member ${member['@odata.id']}:`,
error,
);
return null;
}),
);
const members = await Promise.all(memberPromises);
return members.filter((m: T | null): m is T => m !== null);
}
return [];
} catch (error) {
// If OData query failed, try without parameters
const hasQueryParams = url !== path;
if (hasQueryParams) {
console.warn(
`OData query failed for ${path}, falling back to basic fetch`,
);
try {
const { data } =
await api.get<RedfishCollection<CollectionMember>>(path);
if (data.Members && Array.isArray(data.Members)) {
const memberPromises = data.Members.map((member: CollectionMember) =>
api
.get<T>(member['@odata.id'])
.then((res: { data: T }) => res.data)
.catch((err: Object) => {
console.error(
`Error fetching member ${member['@odata.id']}:`,
err,
);
return null;
}),
);
const members = await Promise.all(memberPromises);
return members.filter((m: T | null): m is T => m !== null);
}
} catch (fallbackError) {
console.error(`Failed to fetch collection ${path}:`, fallbackError);
throw fallbackError;
}
}
console.error(`Failed to fetch collection ${path}:`, error);
throw error;
}
}
/**
* TanStack Query hook for fetching a Redfish collection
*
* @param path - Collection path
* @param options - Fetch options
* @returns TanStack Query result
*/
export function useRedfishCollection<T>(
path: string,
options: FetchCollectionOptions = {},
) {
// Get ServiceRoot to check OData support
const { data: serviceRoot } = useRedfishRoot();
// Compute whether expand is supported
const canExpand = computed(() => supportsExpandQuery(serviceRoot.value));
// Build query parameters for normalization
const queryParams: RedfishQueryParameters = {};
if (options.expand) {
queryParams.$expand = { $levels: options.expandLevels || 1 };
}
if (options.select && options.select.length > 0) {
queryParams.$select = options.select;
}
if (options.filter) {
queryParams.$filter = options.filter;
}
// Normalize query parameters for stable cache keys
const normalizedParams = normalizeRedfishQueryParameters(queryParams);
return useQuery({
queryKey: ['redfish', 'collection', path, normalizedParams],
queryFn: () => fetchCollection<T>(path, options, canExpand.value),
enabled: computed(() => !!serviceRoot.value),
refetchOnMount: false, // Don't refetch when component remounts
refetchOnWindowFocus: false, // Don't refetch when window regains focus
refetchOnReconnect: false,
retry: 2,
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
});
}
|