@yext/search-core
Version:
Typescript Networking Library for the Yext Search API
72 lines • 2.74 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpServiceImpl = void 0;
const cross_fetch_1 = __importDefault(require("cross-fetch"));
const urlutils_1 = require("../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.
*/
class HttpServiceImpl {
/**
* Perform a GET request
*/
get(url, queryParams, clientSdk, authToken) {
return fetch(url, queryParams, {
method: RequestMethods.GET,
mode: 'cors',
credentials: 'include',
headers: Object.assign({ 'Client-SDK': formatAsHttpHeader(clientSdk) }, (authToken && { Authorization: `Bearer ${authToken}` }))
}).then(res => res.json());
}
/**
* Perform a POST request
*/
post(url, queryParams, body, clientSdk, authToken) {
const sanitizedBodyParams = (0, urlutils_1.sanitizeQueryParams)(body);
return fetch(url, queryParams, Object.assign(Object.assign({ method: RequestMethods.POST, body: JSON.stringify(sanitizedBodyParams), mode: 'cors' }, (authToken && { credentials: 'include' })), { headers: Object.assign({ 'Client-SDK': formatAsHttpHeader(clientSdk), 'Content-Type': 'application/json' }, (authToken && { Authorization: `Bearer ${authToken}` })) }))
.then(res => res.json());
}
}
exports.HttpServiceImpl = HttpServiceImpl;
/**
* Perform a fetch, using the polyfill if needed.
*/
function fetch(url, queryParams, reqInit) {
const urlWithParams = (0, urlutils_1.addParamsToURL)(url, queryParams);
if (typeof (window) !== 'undefined' && window.fetch) {
return window.fetch(urlWithParams, reqInit);
}
return (0, cross_fetch_1.default)(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((combinedHeader, currentKey) => {
const httpFormattedHeader = `${currentKey}=${clientSdk[currentKey]}`;
return combinedHeader ? `${combinedHeader}, ${httpFormattedHeader}` : httpFormattedHeader;
}, '');
}
//# sourceMappingURL=HttpServiceImpl.js.map