RESTDataSource: add didReceiveResponse method (#1325)

This commit is contained in:
Gauthier Rodaro 2018-07-11 15:17:03 +02:00 committed by Martijn Walraven
parent 890e10b799
commit ecc56690df

View file

@ -48,6 +48,17 @@ export abstract class RESTDataSource<TContext = any> {
} }
} }
protected async didReceiveResponse<TResult = any>(
response: Response,
): Promise<TResult> {
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.startsWith('application/json')) {
return response.json();
} else {
return response.text() as Promise<any>;
}
}
protected async didReceiveErrorResponse<TResult = any>( protected async didReceiveErrorResponse<TResult = any>(
response: Response, response: Response,
): Promise<TResult> { ): Promise<TResult> {
@ -156,13 +167,7 @@ export abstract class RESTDataSource<TContext = any> {
return this.trace(`${options.method || 'GET'} ${url}`, async () => { return this.trace(`${options.method || 'GET'} ${url}`, async () => {
const response = await this.httpCache.fetch(request); const response = await this.httpCache.fetch(request);
if (response.ok) { if (response.ok) {
const contentType = response.headers.get('Content-Type'); return this.didReceiveResponse(response);
if (contentType && contentType.startsWith('application/json')) {
return response.json();
} else {
return response.text();
}
} else { } else {
return this.didReceiveErrorResponse(response); return this.didReceiveErrorResponse(response);
} }