@yext/search-core
Version:
Typescript Networking Library for the Yext Search API
80 lines • 3.04 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
import crossFetch from 'cross-fetch';
import { addParamsToURL, sanitizeQueryParams } from '../utils/urlutils';
/**
* Available HTTP request methods
*/
var RequestMethods;
(function (RequestMethods) {
RequestMethods["GET"] = "get";
RequestMethods["POST"] = "post";
})(RequestMethods || (RequestMethods = {}));
/**
* HttpServiceImpl is a wrapper around the native implementation of AJAX
* related matters.
*/
var HttpServiceImpl = /** @class */ (function () {
function HttpServiceImpl() {
}
/**
* Perform a GET request
*/
HttpServiceImpl.prototype.get = function (url, queryParams, clientSdk, authToken) {
return fetch(url, queryParams, {
method: RequestMethods.GET,
mode: 'cors',
credentials: 'include',
headers: __assign({ 'Client-SDK': formatAsHttpHeader(clientSdk) }, (authToken && { Authorization: "Bearer ".concat(authToken) }))
}).then(function (res) { return res.json(); });
};
/**
* Perform a POST request
*/
HttpServiceImpl.prototype.post = function (url, queryParams, body, clientSdk, authToken) {
var sanitizedBodyParams = sanitizeQueryParams(body);
return fetch(url, queryParams, __assign(__assign({ method: RequestMethods.POST, body: JSON.stringify(sanitizedBodyParams), mode: 'cors' }, (authToken && { credentials: 'include' })), { headers: __assign({ 'Client-SDK': formatAsHttpHeader(clientSdk), 'Content-Type': 'application/json' }, (authToken && { Authorization: "Bearer ".concat(authToken) })) }))
.then(function (res) { return res.json(); });
};
return HttpServiceImpl;
}());
export { HttpServiceImpl };
/**
* Perform a fetch, using the polyfill if needed.
*/
function fetch(url, queryParams, reqInit) {
var urlWithParams = addParamsToURL(url, queryParams);
if (typeof (window) !== 'undefined' && window.fetch) {
return window.fetch(urlWithParams, reqInit);
}
return crossFetch(urlWithParams, reqInit);
}
/**
* Converts the JSON representing the Client-SDK agents into the expected HTTP header format.
*
* @example
* Input clientSdk:
* \{
* ANSWERS_CORE: '123',
* CUSTOM_AGENT: '456'
* \}
*
* Output HTTP header:
* 'ANSWERS_CORE=123, CUSTOM_AGENT=456'
*/
function formatAsHttpHeader(clientSdk) {
return Object.keys(clientSdk).reduce(function (combinedHeader, currentKey) {
var httpFormattedHeader = "".concat(currentKey, "=").concat(clientSdk[currentKey]);
return combinedHeader ? "".concat(combinedHeader, ", ").concat(httpFormattedHeader) : httpFormattedHeader;
}, '');
}
//# sourceMappingURL=HttpServiceImpl.js.map