@eclipse-ditto/ditto-javascript-client-dom
Version:
DOM implementation of Eclipse Ditto JavaScript API to be used in browsers.
75 lines • 2.82 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
*/
import { PutResponse } from '../../model/response';
/**
* Handle to send requests.
*/
export class RequestSender {
/**
* Fetches the specified request and returns an object of type T.
*
* @typeParam T - The type of object to return
* @param options - The options to use for the request.
* @returns A Promise for the specified object
*/
fetchJsonRequest(options) {
return this.fetchGenericJsonRequest(options).then(response => options.parser(response.body));
}
/**
* Fetches the specified request and returns an object of type T.
*
* @typeParam T - The type of object to return
* @param options - The options to use for the request.
* @returns A Promise for the specified object
*/
fetchFormRequest(options) {
return this.fetchRequest(Object.assign(Object.assign({}, options), { payload: options.payload
? this.mapToQueryParams(options.payload)
: undefined })).then(response => options.parser(response.body));
}
mapToQueryParams(map) {
let result = '';
map.forEach((value, key) => {
result += `&${key}=${value}`;
});
return result.substring(1);
}
/**
* Fetches the specified request and returns an object of type T.
*
* @typeParam T - The type of object to return
* @param options - The options to use for the request.
* @returns A Promise for the specified object
*/
fetchPutRequest(options) {
return this.fetchGenericJsonRequest(options).then(response => {
if (response.status === 201) {
return new PutResponse(options.parser(response.body), response.status, response.headers);
}
if (response.status === 204) {
return new PutResponse(null, response.status, response.headers);
}
return Promise.reject(`Received unknown status code: ${response.status}`);
});
}
/**
* Fetches the specified request and checks if the request was successful.
*
* @param options - The options to use for the request.
* @returns A Promise for the response
*/
fetchGenericJsonRequest(options) {
return this.fetchRequest(Object.assign(Object.assign({}, options), { payload: JSON.stringify(options.payload) }));
}
}
//# sourceMappingURL=request-sender.js.map