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/graphql / dist / proxy.js
Size: Mime:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * @file @todo split up
 */
/* eslint-disable import/first */
/* eslint-disable import/no-namespace */
// import { Cookie, CookieJar } from 'tough-cookie'
const http_proxy_middleware_1 = __importDefault(require("http-proxy-middleware"));
const express_1 = __importDefault(require("express"));
const cookie_parser_1 = __importDefault(require("cookie-parser"));
const body_parser_1 = __importDefault(require("body-parser"));
const exotic_1 = require("exotic");
// import { cookies } from '@skava/modules/___dist/persistance/cookies'
// import { omniStorage as oneStorage } from '@skava/modules/___dist/persistance'
// import { cacheResponse, clearCache, nocache } from './deps/networkCache'
const node_http_proxy_json_1 = __importDefault(require("@skava/modules/___dist/_forks/node-http-proxy-json"));
const config = __importStar(require("./bootstrapper/api/config"));
const transformRequestProxy_1 = require("./deps/transformRequestProxy");
const cookieHacker_1 = require("./deps/cookieHacker");
const encodeBody_1 = require("./deps/encodeBody");
const fromReqResToDebug_1 = require("./deps/fromReqResToDebug");
const { cookieConfig, API_LAYER_ENV, STREAM_API_LAYER } = config;
// ----- we use this so we can just call /api/category not /category
// ----- always enabled, this way we can know it goes to api
// ----- and is not requesting a page or other data
// const pathRewrite = {
//   '^/api': '/',
// }
const getPathRewrite = (route) => {
    if (API_LAYER_ENV !== STREAM_API_LAYER) {
        const basepath = (`^/api${route}`);
        return {
            [basepath]: ''
        };
    }
    return {
        '^/api': "/"
    };
};
const getProxyUrl = (route, callType) => {
    const proxyConfig = {
        changeOrigin: true,
        secure: true,
        pathRewrite: getPathRewrite(route),
        onProxyRes,
        onProxyReq,
        dataType: 'json',
        logLevel: 'silent',
        // target: route,
        target: transformRequestProxy_1.getURL(route, callType),
    };
    // proxyConfig.target = getURL(route, callType)
    return proxyConfig;
};
// https://www.npmjs.com/package/http-proxy#options
// ^ cookie rewrite
// eslint-disable-next-line
function onProxyRes(proxyRes, req, res, next) {
    console.log('[uxui-api] onProxyRes', proxyRes);
    const { authCookies, onCookie } = cookieHacker_1.createCookieHacker();
    // isEmpty(authCookies) &&
    if (exotic_1.isArray(proxyRes.headers['set-cookie'])) {
        // oneStorage.removeItem('authCookies')
        proxyRes.headers['set-cookie'].map(onCookie);
        node_http_proxy_json_1.default(res, proxyRes, body => {
            // const safe = 'authCookies' + authCookies.join('_')
            // oneStorage.setItem(safe, authCookies)
            body.cookies = authCookies;
            // if (process.env.SERVER_NETWORK_CACHE === true) {
            //   cacheResponse(res, body)
            // }
            console.log(body, '----------------------------------------><><><');
            if (body) {
                return body;
            }
            return {
                responseCode: proxyRes.statusCode
            };
        });
    }
    else {
        node_http_proxy_json_1.default(res, proxyRes, body => {
            // if (process.env.SERVER_NETWORK_CACHE === 'true') {
            //   cacheResponse(res, body)
            // }
            console.log(body, '----------------------------------------><><><');
            if (body) {
                return body;
            }
            return {
                responseCode: proxyRes.statusCode
            };
        });
    }
    delete proxyRes.headers['set-cookie'];
    proxyRes.headers['set-cookie'] = authCookies;
}
// eslint-disable-next-line
function onProxyReq(proxyReq, req, res, next) {
    console.log('[uxui-api] onProxyReq', proxyReq);
    const requestCookies = req.cookies;
    console.log('onProxyReq______', {
        requestCookies,
        cookieMagic: global.cookieMagic,
    });
    // require('fliplog').quick({
    //   // proxyReq,
    //   req,
    // })
    // console.log({ proxyheaders: proxyReq.headers })
    // console.log({ headers: req.headers })
    // const safeRequestCookies = req.cookies || req.headers._cookie || req.signedCookies
    // const requestCookies = isObj(safeRequestCookies) && Object.keys(safeRequestCookies).length > 0
    //   ? safeRequestCookies
    //   : global.cookieMagic
    // console.log('onProxyReq______', {
    //   requestCookies,
    //   cook: req.cookies,
    //   cookiez: req.headers.cookie,
    //   _cookie: req.headers._cookie,
    //   signedCookies: req.signedCookies,
    //   cookieMagic: global.cookieMagic,
    // })
    if (process.env.TEST_COOKIE_SCOPE) {
        // testing - can do .forEach & console.assert too
        Object.keys(requestCookies).forEach(key => {
            if (global.cookieMagic[key] !== requestCookies[key]) {
                throw new Error('PROVEN FIX');
            }
            else {
                console.log('was the same value for ' + key);
            }
        });
    }
    // const HORRIBLE_GLOBALS_THANKS_TO_APOLLO = fromObjCookiesToString(global.cookieMagic)
    const HORRIBLE_GLOBALS_THANKS_TO_APOLLO = cookieHacker_1.fromObjCookiesToString(requestCookies);
    proxyReq.setHeader('Cookie', HORRIBLE_GLOBALS_THANKS_TO_APOLLO);
    //   console.log('HORRIBLE_GLOBALS_THANKS_TO_APOLLO', HORRIBLE_GLOBALS_THANKS_TO_APOLLO)
    console.log("Change IsEmpty condition");
    //  @todo @bhargavi @anto Change isEmpty
    if (req.method !== 'GET' && (!exotic_1.isEmpty(req.body) || exotic_1.isObj(req.body))) {
        console.log('[uxui-apis] encoding body');
        const reqBody = req.body;
        delete req.body;
        // console.log('Old Body', reqBody)
        const body = API_LAYER_ENV === STREAM_API_LAYER
            ? encodeBody_1.encodeBody(reqBody)
            : JSON.stringify(reqBody);
        if (process.env.LOG_REQUEST_POST_BODY) {
            console.log('[uxui-apis] ', { reqBody, body });
        }
        console.log(reqBody, body, body.length);
        proxyReq.setHeader('content-type', 'application/x-www-form-urlencoded');
        proxyReq.setHeader('content-length', body.length);
        proxyReq.write(body);
        proxyReq.end();
    }
    else {
        console.log('[uxui-apis] not encoding body');
        if (process.env.LOG_REQUEST_PROXY) {
            console.log('[uxui-apis] LOG_REQUEST_PROXY', req);
        }
    }
}
const proxyApi = api => {
    const fromRouteToProxy = route => {
        const proxyConfig = getProxyUrl(route, transformRequestProxy_1.callDetails[route]);
        const proxyMiddlewareForRoute = http_proxy_middleware_1.default(proxyConfig);
        // @note removed for now
        // createProxyCache
        api.use(route, proxyMiddlewareForRoute);
        return api;
    };
    transformRequestProxy_1.endpoints.map(fromRouteToProxy);
    return api;
    // @NOTE when we need more advanced config, we do not put it in endpoints
    // api.use('/user', proxy(proxyConfig))
    // 20170815175328
    // http://localhost:3000/api/category/top?campaignId=2495&subcategory=true
    // http://localhost:4000/api/search?campaignId=2495&offset=0&limit=15&locale=en_US&search=shoe
};
// @NOTE may want to not use this in test env
const api = express_1.default();
exports.api = api;
api.use(function (req, res, next) {
    res.req = req;
    const reqRes = {
        req,
        res,
    };
    fromReqResToDebug_1.logReqAndOrRes(reqRes);
    next();
});
api.use(cookie_parser_1.default());
api.use(body_parser_1.default.json());
api.use(body_parser_1.default.urlencoded({
    extended: true,
}));
exports.default = api;
//# sourceMappingURL=proxy.js.map