-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathbatch-response-deserializer.ts
217 lines (202 loc) · 6.98 KB
/
batch-response-deserializer.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
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
import { createLogger, ErrorWithCause } from '@sap-cloud-sdk/util';
import {
ErrorResponse,
ReadResponse,
WriteResponse,
WriteResponses
} from '../../batch-response';
import { Constructable, EntityBase } from '../../entity';
import { EntityDeserializer } from '../../entity-deserializer';
import { ResponseDataAccessor } from '../../response-data-accessor';
import { ResponseData, isHttpSuccessCode } from './batch-response-parser';
const logger = createLogger({
package: 'core',
messageContext: 'batch-response-transformer'
});
/**
* Represents the state needed to deserialize a parsed batch response using OData version specific deserialization data access.
*/
export class BatchResponseDeserializer {
/**
* Creates an instance of BatchResponseTransformer.
* @param entityToConstructorMap A map that holds the entity type to constructor mapping.
* @param responseDataAccessor Response data access module.
* @param deserializer Entity deserializer.
*/
constructor(
private readonly entityToConstructorMap: Record<
string,
Constructable<EntityBase>
>,
private readonly responseDataAccessor: ResponseDataAccessor,
private readonly deserializer: EntityDeserializer
) {}
/**
* Deserialize the parsed batch response.
* @param parsedBatchResponse Two dimensional list of parsed batch sub responses.
* @returns An array of parsed sub responses of the batch response.
*/
deserializeBatchResponse(
parsedBatchResponse: (ResponseData[] | ResponseData)[]
): (ErrorResponse | ReadResponse | WriteResponses)[] {
return parsedBatchResponse.map(responseData => {
if (Array.isArray(responseData)) {
return this.deserializeChangeSet(responseData);
}
return isHttpSuccessCode(responseData.httpCode)
? this.deserializeRetrieveResponse(responseData)
: this.deserializeErrorResponse(responseData);
});
}
private deserializeRetrieveResponse(
responseData: ResponseData
): ReadResponse {
return {
...responseData,
type: this.getConstructor(responseData.body)!,
as: asReadResponse(
responseData.body,
this.responseDataAccessor,
this.deserializer
),
isSuccess: () => true
};
}
private deserializeErrorResponse(responseData: ResponseData): ErrorResponse {
return { ...responseData, isSuccess: () => false };
}
private deserializeChangeSetSubResponse(
responseData: ResponseData
): WriteResponse {
return {
...responseData,
type: this.getConstructor(responseData.body),
as: asWriteResponse(
responseData.body,
this.responseDataAccessor,
this.deserializer
)
};
}
private deserializeChangeSet(changesetData: ResponseData[]): WriteResponses {
return {
responses: changesetData.map(subResponseData =>
this.deserializeChangeSetSubResponse(subResponseData)
),
isSuccess: () => true
};
}
/**
* Retrieve the constructor for a specific single response body.
* @param responseBody The body of a single response as an object.
* @returns The constructor if found in the mapping, undefined otherwise.
*/
private getConstructor(
responseBody: Record<string, any>
): Constructable<EntityBase> | undefined {
const entityJson = this.responseDataAccessor.isCollectionResult(
responseBody
)
? this.responseDataAccessor.getCollectionResult(responseBody)[0]
: this.responseDataAccessor.getSingleResult(responseBody);
const entityUri = entityJson?.__metadata?.uri;
if (entityUri) {
return this.entityToConstructorMap[
parseEntityNameFromMetadataUri(entityUri)
];
}
logger.warn('Could not parse constructor from response body.');
}
}
/**
* Deserialize the parsed batch response.
* @param parsedBatchResponse Two dimensional list of parsed batch sub responses.
* @param entityToConstructorMap A map that holds the entity type to constructor mapping.
* @param responseDataAccessor Response data access module.
* @param deserializer Entity deserializer.
* @returns An array of parsed sub responses of the batch response.
*/
export function deserializeBatchResponse(
parsedBatchResponse: (ResponseData[] | ResponseData)[],
entityToConstructorMap: Record<string, Constructable<EntityBase>>,
responseDataAccessor: ResponseDataAccessor,
deserializer: EntityDeserializer
): (ErrorResponse | ReadResponse | WriteResponses)[] {
return new BatchResponseDeserializer(
entityToConstructorMap,
responseDataAccessor,
deserializer
).deserializeBatchResponse(parsedBatchResponse);
}
/**
* Create a function to transform the parsed response body to a list of entities of the given type or an error.
* @param body The parsed JSON reponse body.
* @param responseDataAccessor Response data access module.
* @param deserializer Entity deserializer.
* @returns A function to be used for transformation of the read response.
*/
function asReadResponse(
body: any,
responseDataAccessor: ResponseDataAccessor,
deserializer: EntityDeserializer
) {
return <EntityT extends EntityBase>(
constructor: Constructable<EntityT>
): EntityT[] => {
if (body.error) {
throw new ErrorWithCause('Could not parse read response.', body.error);
}
if (responseDataAccessor.isCollectionResult(body)) {
return responseDataAccessor
.getCollectionResult(body)
.map(r => deserializer.deserializeEntity(r, constructor));
}
return [
deserializer.deserializeEntity(
responseDataAccessor.getSingleResult(body),
constructor
)
];
};
}
/**
* Create a function to transform the parsed response body to an entity of the given type.
* @param body The parsed JSON reponse body.
* @param responseDataAccessor Response data access module.
* @param deserializer Entity deserializer.
* @returns A function to be used for transformation of the write response.
*/
function asWriteResponse(
body: any,
responseDataAccessor: ResponseDataAccessor,
deserializer: EntityDeserializer
) {
return <EntityT extends EntityBase>(constructor: Constructable<EntityT>) =>
deserializer.deserializeEntity(
responseDataAccessor.getSingleResult(body),
constructor
);
}
/**
* Parse the entity name from the metadata uri. This should be the `__metadata` property of a single entity in the response.
* @param uri The URI to parse the entity name from
* @returns The entity name.
*/
export function parseEntityNameFromMetadataUri(uri: string): string {
if (!uri) {
throw new Error(
`Could not retrieve entity name from metadata. URI was: '${uri}'.`
);
}
const [pathBeforeQuery] = uri.split('?');
const [pathBeforeKeys] = pathBeforeQuery.split('(');
const uriParts = pathBeforeKeys.split('/');
// Remove another part in case of a trailing slash
const entityName = uriParts.pop() || uriParts.pop();
if (!entityName) {
throw Error(
`Could not retrieve entity name from metadata. Unknown URI format. URI was: '${uri}'.`
);
}
return entityName;
}