/
response-data-accessor.ts
87 lines (77 loc) · 2.64 KB
/
response-data-accessor.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
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
import { createLogger } from '@sap-cloud-sdk/util';
import { ResponseDataAccessor } from '../../odata-common';
const logger = createLogger({
package: 'core',
messageContext: 'response-data-accessor'
});
/**
* Methods to extract the data from OData v2 responses.
*/
/**
* Extract the collection data from the response.
* If the data does not contain a collection an empty array is returned.
* @param data - Response of the OData v2 service
* @returns any[] - Collection extracted from the response
*/
export function getCollectionResult(data): any[] {
validateCollectionResult(data);
return isCollectionResult(data) ? data?.d?.results : [];
}
/**
* Checks if the data contains a collection result.
* @param data - Response of the OData service.
* @returns True if the data is a collection result.
*/
export function isCollectionResult(data): boolean {
return Array.isArray(data?.d?.results);
}
function validateCollectionResult(data): void {
if (!isCollectionResult(data)) {
logger.warn(
'The given reponse data does not have the standard OData v2 format for collections.'
);
}
}
/**
* Extract the collection data from the one to many link response.
* If the data does not contain a collection an empty array is returned.
* @param data - Response of the one to many link
* @returns any[] - Collection extracted from the response
*/
export function getLinkedCollectionResult(data): any[] {
if (Array.isArray(data?.results)) {
return data.results;
}
return Array.isArray(data) ? data : [];
}
/**
* Parses the data of a single result.
* @param data - Response of the OData service.
* @returns The single result object if existent, an empty object otherwise.
*/
export function getSingleResult(data: any): Record<string, any> {
validateSingleResult(data);
return isSingleResultAsCollection(data) ? data?.d?.results : data?.d || {};
}
// Workaround to be compatible with services that wrongly implement the OData v2 protocol and serve single responses in the same format as collections
function isSingleResultAsCollection(data): boolean {
return !!data?.d?.results && !isCollectionResult(data);
}
function validateSingleResult(data): void {
if (isSingleResultAsCollection(data)) {
logger.warn(
'The given reponse data has the format for collections instead of the standard OData v2 format for single results.'
);
}
if (!data?.d) {
logger.warn(
'The given reponse data does not have the standard OData v2 format for single results.'
);
}
}
export const responseDataAccessorV2: ResponseDataAccessor = {
getCollectionResult,
getLinkedCollectionResult,
getSingleResult,
isCollectionResult
};