-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathodata-request.ts
282 lines (256 loc) · 8.65 KB
/
odata-request.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
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
import { errorWithCause, propertyExists } from '@sap-cloud-sdk/util';
import { Destination, sanitizeDestination } from '../../../scp-cf';
import {
removeLeadingSlashes,
removeSlashes,
removeTrailingSlashes
} from '../../../util/remove-slashes';
import { HttpResponse, executeHttpRequest } from '../../../http-client';
import {
filterNullishValues,
getHeader,
getHeaders,
getHeaderValue,
mergeHeaders
} from '../../../header-builder';
// TODO: The buildCsrfHeaders import cannot be combined with the rest of the other headers due to circular dependencies
import { buildCsrfHeaders } from '../../../header-builder/csrf-token-header';
// TODO: The buildHeadersForDestination import cannot be combined with the rest of the other headers due to circular dependencies
import { buildHeadersForDestination } from '../../../header-builder/header-builder-for-destination';
import { ODataRequestConfig } from './odata-request-config';
import { isWithETag } from './odata-request-traits';
/**
* OData request configuration for an entity type.
*
* @typeparam EntityT - Type of the entity to setup a request for
*/
export class ODataRequest<RequestConfigT extends ODataRequestConfig> {
/**
* Creates an instance of ODataRequest.
*
* @param config - Configuration of the request
* @param _destination - Destination to setup the request against
* @memberof ODataRequest
*/
constructor(
public config: RequestConfigT,
private _destination?: Destination | undefined
) {}
set destination(dest: Destination | undefined) {
this._destination = dest && sanitizeDestination(dest);
}
get destination(): Destination | undefined {
return this._destination;
}
/**
* Constructs an absolute URL for the given request.
* @returns The absolute URL for the request
*/
url(): string {
return `${removeTrailingSlashes(this.resourceUrl())}${this.query()}`;
}
/**
* Constructs a URL relative to the destination.
* @param includeServicePath Whether or not to include the service path in the URL.
* @returns The relative URL for the request.
*/
relativeUrl(includeServicePath = true): string {
return `${removeTrailingSlashes(
this.relativeResourceUrl(includeServicePath)
)}${this.query()}`;
}
/**
* Specifies whether the destination needs a specific authentication or not.
*
* @returns A boolean value that specifies whether the destination needs authentication or not
* @memberof ODataRequest
*/
needsAuthentication(): boolean {
return (
!!this.destination &&
this.destination.authentication !== 'NoAuthentication'
);
}
/**
* Returns the service URL for a given OData request.
* @returns The URL of the service the given entity belongs to
*/
serviceUrl(): string {
if (!this.destination) {
throw Error('The destination is undefined.');
}
const systemUrl = this.destination.url;
const servicePath =
typeof this.config.customServicePath === 'undefined'
? this.config.defaultServicePath
: this.config.customServicePath;
return `${removeTrailingSlashes(systemUrl)}/${removeSlashes(servicePath)}`;
}
/**
* Returns the service URL relative to the url of the destination for a given OData request.
* @returns The relative URL of the service the given entity belongs to.
*/
relativeServiceUrl(): string {
const servicePath =
typeof this.config.customServicePath === 'undefined'
? this.config.defaultServicePath
: this.config.customServicePath;
return `${removeSlashes(servicePath)}`;
}
/**
* Returns the URL to a specific OData .resource, i.e. the entity collection.
* @returns The URL of the resource
*/
resourceUrl(): string {
return `${removeTrailingSlashes(
this.serviceUrl()
)}/${this.config.resourcePath()}`;
}
/**
* Returns the relative URL to a specific OData resource.
* @param includeServicePath Whether or not to include the service path in the URL.
* @returns The relative URL of the resource.
*/
relativeResourceUrl(includeServicePath = true): string {
const baseUrl = includeServicePath
? removeTrailingSlashes(this.relativeServiceUrl())
: '';
const url = `${baseUrl}/${this.config.resourcePath()}`;
return removeLeadingSlashes(url);
}
/**
* Get query parameters as string. Leads with `?` if there are parameters to return.
*
* @returns Query parameter string
*/
query(): string {
const queryParameters = {
...this.config.queryParameters(),
...this.config.customQueryParameters
};
const query = Object.entries(queryParameters)
.map(([key, value]) => `${key}=${value}`)
.join('&');
return query.length ? `?${query}` : '';
}
/**
* Create object containing all headers, including custom headers for the given request.
*
* @returns Key-value pairs where the key is the name of a header property and the value is the respective value
*/
async headers(): Promise<Record<string, any>> {
try {
if (!this.destination) {
throw Error('The destination is undefined.');
}
const destinationRelatedHeaders = await buildHeadersForDestination(
this.destination,
this.config.customHeaders
);
const csrfHeaders =
this.config.method === 'get'
? {}
: await this.getCsrfHeaders(destinationRelatedHeaders);
return {
...destinationRelatedHeaders,
...csrfHeaders,
...this.defaultHeaders(),
...this.eTagHeaders(),
...this.customHeaders()
};
} catch (error) {
return Promise.reject(
errorWithCause('Constructing headers for OData request failed!', error)
);
}
}
/**
* Get all custom headers.
* @returns Key-value pairs where the key is the name of a header property and the value is the respective value
*/
customHeaders(): Record<string, any> {
return this.config.customHeaders;
}
/**
* Get all default headers. If custom headers are set, those take precedence.
* @returns Key-value pairs where the key is the name of a header property and the value is the respective value
*/
defaultHeaders(): Record<string, any> {
const customDefaultHeaders = getHeaders(
Object.keys(this.config.defaultHeaders),
this.customHeaders()
);
return mergeHeaders(
filterNullishValues(this.config.defaultHeaders),
customDefaultHeaders
);
}
/**
* Get the eTag related headers, e. g. `if-match`.
* @returns Key-value pairs where the key is the name of a header property and the value is the respective value
*/
eTagHeaders(): Record<string, string> {
if (getHeaderValue('if-match', this.customHeaders())) {
return getHeader('if-match', this.customHeaders());
}
const eTag = isWithETag(this.config)
? this.config.versionIdentifierIgnored
? '*'
: this.config.eTag
: undefined;
return filterNullishValues({ 'if-match': eTag });
}
/**
* Execute the given request and return the according promise.
*
* @returns Promise resolving to the requested data
*/
async execute(): Promise<HttpResponse> {
const destination = this.destination;
if (!destination) {
throw Error('The destination cannot be undefined.');
}
return executeHttpRequest(destination, {
headers: await this.headers(),
url: this.relativeUrl(),
method: this.config.method,
data: this.config.payload
}).catch(error =>
Promise.reject(
constructError(error, this.config.method, this.serviceUrl())
)
);
}
private async getCsrfHeaders(
destinationRelatedHeaders: Record<string, string>
): Promise<Record<string, string>> {
const customCsrfHeaders = getHeader(
'x-csrf-token',
this.config.customHeaders
);
return Object.keys(customCsrfHeaders).length
? customCsrfHeaders
: buildCsrfHeaders(this.destination!, {
headers: destinationRelatedHeaders,
url: this.relativeServiceUrl()
});
}
}
function constructError(error, requestMethod: string, url: string): Error {
if (error.isAxiosError) {
const defaultMessage = `${requestMethod} request to ${url} failed!`;
const s4SpecificMessage = propertyExists(error, 'response', 'data', 'error')
? messageFromS4ErrorResponse(error)
: '';
const message = [defaultMessage, s4SpecificMessage].join(' ');
return errorWithCause(message, error);
}
return error;
}
function messageFromS4ErrorResponse(error): string {
return `${
propertyExists(error.response.data.error, 'message', 'value')
? error.response.data.error.message.value
: ''
}\n${JSON.stringify(error.response.data.error)}`;
}