@eclipse-ditto/ditto-javascript-client-node
Version:
Node.js(r) implementation of Eclipse Ditto JavaScript API.
79 lines • 2.98 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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestSender = void 0;
const response_1 = require("../../model/response");
/**
* Handle to send requests.
*/
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 response_1.PutResponse(options.parser(response.body), response.status, response.headers);
}
if (response.status === 204) {
return new response_1.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) }));
}
}
exports.RequestSender = RequestSender;
//# sourceMappingURL=request-sender.js.map