@eclipse-ditto/ditto-javascript-client-dom
Version:
DOM implementation of Eclipse Ditto JavaScript API to be used in browsers.
52 lines • 1.91 kB
JavaScript
/*!
* Copyright (c) 2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
export class FetchRequester {
doRequest(method, url, header, body) {
// Use AbortSignal.timeout() for cleaner timeout handling when available
const signal = this.timeout !== undefined
? AbortSignal.timeout(this.timeout)
: undefined;
return fetch(this.prepareRequest(method, url, header, body, signal))
.then(response => {
const headers = new Map();
response.headers.forEach((v, k) => headers.set(k, v));
return response.json()
.then(json => ({ headers, status: response.status, body: json }), () => ({ headers, status: response.status, body: undefined }));
})
.catch(error => {
throw error;
});
}
/**
* Builds a Request object to perform a fetch request with.
*
* @param method - The type of action to perform.
* @param url - The Url to send the request to.
* @param header - The headers of the request.
* @param body - The payload to send with the request.
* @param signal - Optional abort signal for timeout handling.
* @return the builder.
*/
prepareRequest(method, url, header, body, signal) {
const headers = new Headers();
header.forEach((v, k) => headers.append(k, v));
return new Request(url, {
headers,
method,
body,
mode: 'cors',
signal
});
}
}
//# sourceMappingURL=fetch-http.js.map