Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/request / dist / adapters / fetch.js
Size: Mime:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
const exotic_1 = require("exotic");
const config_1 = require("../config");
const fromRequestToSerialized_1 = require("../deps/fromRequestToSerialized");
const encodeBody_1 = require("../deps/encodeBody");
const fromParamsToStringified_1 = require("../deps/fromParamsToStringified");
const toHeaders_1 = require("../deps/toHeaders");
const fromStoreToParams = (store) => {
    // @TODO @james this needs some love, I hacked it to get it functional (from @michael)
    // store.has('tapParams')
    //   ? store.get('tapParams')(store.get('params') as ParamsObj)
    //   : store.get('params')
    if (store.has('params') === true) {
        const params = store.get('params');
        // console.log('fromStoreToParams - has params')
        return params;
        /**
         * @throws @invalid
         * => { 'isStringied' => '[object Object]', 'two' => '2' } }
         * @example return new URLSearchParams(params)
         */
    }
    else {
        // console.warn('fromStoreToParams - has no params')
        return exotic_1.EMPTY_OBJ;
    }
};
exports.fromStoreToParams = fromStoreToParams;
// @todo passing in string because serialize
// but could adapt here
const setParamsOnSearchParams = (params, urlObj) => {
    // @note - was just checking !params
    if (params !== '') {
        // Append params to existing params in the path
        const urlSearchParamEntries = new url_1.URLSearchParams(params);
        for (const [name, value] of urlSearchParamEntries) {
            if (!urlObj) {
                const stringifiedParams = JSON.stringify(params, undefined, 2);
                throw new TypeError(`
          did not pass url! ${stringifiedParams}
          url: ${urlObj}
        `);
            }
            if (urlObj.searchParams.has(name) === true) {
                console.warn('[1request] avoided duplicated param, sorry eh');
                console.log({ [name]: value }, '\n\n');
            }
            else {
                urlObj.searchParams.append(name, value);
            }
        }
    }
    else {
        // console.warn('no params - only warn if we have json type')
        // console.log({ tappedParams, params })
    }
};
exports.setParamsOnSearchParams = setParamsOnSearchParams;
/**
 * @note - this gets the urlObj from the store
 *         then appends serialized search params
 */
const setPostParams = (store, init) => {
    const urlObj = store.get('urlObj');
    // @todo @@perf - we have UrlSearchParams returned from here
    const tappedParams = fromStoreToParams(store);
    const params = fromParamsToStringified_1.fromParamsToStringified(tappedParams);
    // debug
    // console.log('setPostParams', { tappedParams, params })
    setParamsOnSearchParams(params, urlObj);
    init.url = urlObj;
};
exports.setPostParams = setPostParams;
function assignDefaultContentType(scoped) {
    const contentType = scoped.headers.get('Content-Type') || false;
    // cloned, immutable
    if (contentType === false) {
        scoped.headers.set('Content-Type', 'application/x-www-form-urlencoded');
    }
}
/**
 * @todo @name fetchAdapter
 * @description this started as postAdapter, now needs a bit to finish
 * ^ when we test POST, this should be good to go to finish
 */
function postAdapter(store) {
    const headers = toHeaders_1.cloneHeaders(store.get('headers'));
    const scoped = {
        url: store.get('urlObj'),
        headers,
    };
    // @todo - this duplicates the content-type below...
    assignDefaultContentType(scoped);
    setPostParams(store, scoped);
    const init = {
        headers: scoped.headers,
        body: store.get('body'),
        credentials: store.get('credentials'),
        // @todo @validate
        method: store.get('method'),
    };
    serializeBody(init);
    // const url = decodeURIComponent('' + scoped.url)
    //   .replace(/\\"/g, '"')
    //   .replace(/\"/g, '"')
    const url = '' + scoped.url;
    const request = new Request(url, init);
    return request;
}
exports.postAdapter = postAdapter;
function isValidJSONBody(body) {
    return (body !== undefined &&
        typeof body !== 'string' &&
        !(body instanceof ArrayBuffer));
}
/**
 * We accept arbitrary objects as body and serialize them as JSON
 */
function serializeBody(init) {
    const contentType = init.headers.get('Content-Type') || false;
    if (contentType === 'json' && isValidJSONBody(init.body)) {
        init.body = JSON.stringify(init.body);
        // this may be a problem
        init.headers.set('Content-Type', 'application/json');
    }
    // @todo @@perf for this check
    else if (init.body) {
        init.body = encodeBody_1.encodeBody(init.body);
        config_1.config.get('logger').debug('`encoded` LOG REQ BODY', init.body);
        init.headers.set('Content-Type', 'application/x-www-form-urlencoded');
    }
    // default - get requests and others
    else {
        config_1.config.get('logger').debug('was not a POST request, or had no body');
    }
}
exports.serializeBody = serializeBody;
function adaptRequest(store) {
    const request = postAdapter(store);
    // @todo put it back from context for per-request settings...
    config_1.config
        .get('logger')
        .debug('[1request] doRequest (adaptRequest - pure fetch): ');
    const serialized = fromRequestToSerialized_1.fromRequestToSerialized(request);
    config_1.config.get('logger').info(serialized);
    const requestWithDebug = request;
    // fromRequestToSerialized.bind(request)
    requestWithDebug.toDebug = () => serialized;
    return requestWithDebug;
}
exports.adaptRequest = adaptRequest;
//# sourceMappingURL=fetch.js.map