refactor: move web http client to a new file

This commit is contained in:
Jovan Krunić
2018-12-14 10:52:52 +01:00
parent 83a2c85e05
commit 246dddd5a5
5 changed files with 79 additions and 62 deletions

View File

@@ -12,60 +12,7 @@
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {HttpClient, HttpResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {HttpClientInterface, HttpClientRequest} from '@openstapps/api/lib/httpClientInterface';
/**
* Response with generic for the type of body that is returned from the request
*/
export interface Response<TYPE_OF_BODY> extends HttpResponse<TYPE_OF_BODY> {
body: TYPE_OF_BODY;
statusCode: number;
}
/**
* HttpClient that is based on angular's HttpClient (@TODO: move it to provider or independent package)
*/
@Injectable()
export class StAppsWebHttpClient implements HttpClientInterface {
constructor(private http: HttpClient) {
}
/**
* Make a request
* @param requestConfig Configuration of the request
*/
async request<TYPE_OF_BODY>(
requestConfig: HttpClientRequest,
): Promise<Response<TYPE_OF_BODY>> {
const options: {
[key: string]: any;
observe: 'response';
} = {
body: {},
observe: 'response',
responseType: 'json',
};
if (typeof requestConfig.body !== 'undefined') {
options.body = requestConfig.body;
}
if (typeof requestConfig.headers !== 'undefined') {
options.headers = requestConfig.headers;
}
try {
const response: HttpResponse<TYPE_OF_BODY> = await this.http.request<TYPE_OF_BODY>(
requestConfig.method || 'GET', requestConfig.url.toString(), options)
.toPromise();
return Object.assign(response, {statusCode: response.status, body: response.body || {}});
} catch (err) {
throw Error(err);
}
}
}
/*
Generated class for the DataProvider provider.