"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var qs = tslib_1.__importStar(require("qs"));
var init_1 = require("../init");
var utils_1 = require("./utils");
var validator_1 = require("./validator");
/**
 * @description 双向校验
 */
function createValidateMiddle(hooks) {
    var _this = this;
    return function (req, res, next) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
        var _a, _b, smPath, _c, smBasePath;
        return tslib_1.__generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    _a = req.headers, _b = init_1.X_SM_PATH, smPath = _a[_b], _c = init_1.X_SM_BASEPATH, smBasePath = _a[_c];
                    if (!((smPath || smBasePath) && hooks)) return [3 /*break*/, 2];
                    return [4 /*yield*/, hooks(req, res, { path: smPath, basePath: smBasePath })];
                case 1:
                    _d.sent();
                    _d.label = 2;
                case 2:
                    if (next) {
                        next();
                    }
                    return [2 /*return*/];
            }
        });
    }); };
}
exports.createValidateMiddle = createValidateMiddle;
/**
 * @description http-proxy-middleware
 */
exports.requestMiddleware = createValidateMiddle(function (req, res) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var headers, smConfig, body, bodyType, e_1;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                _a.trys.push([0, 2, , 3]);
                headers = req.headers;
                smConfig = utils_1.getParams(req);
                return [4 /*yield*/, utils_1.getReadableDataAsync(req)];
            case 1:
                body = _a.sent();
                bodyType = headers['content-type'];
                switch (bodyType) {
                    case 'application/json':
                    case 'javascript/json':
                        smConfig.data = smConfig.body = JSON.parse(body);
                        break;
                    // @cc: file
                    case 'multipart/form-data':
                    case 'application/x-www-form-urlencoded':
                        smConfig.form = smConfig.body = qs.parse(body);
                        break;
                }
                req[init_1.X_SM_PARAMS] = smConfig;
                return [3 /*break*/, 3];
            case 2:
                e_1 = _a.sent();
                req[init_1.X_SM_ERROR] = req[init_1.X_SM_ERROR] || [];
                req[init_1.X_SM_ERROR].push("\u63D0\u53D6\u8BF7\u6C42\u53C2\u6570\u9519\u8BEF: " + (e_1.message || e_1));
                return [3 /*break*/, 3];
            case 3: return [2 /*return*/];
        }
    });
}); });
exports.responseHooksFactory = function (cb) { return function (req, res, swagger) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var error, result, bodyType, _a, _b, _c, _d, _e, e_2;
    return tslib_1.__generator(this, function (_f) {
        switch (_f.label) {
            case 0:
                error = req[init_1.X_SM_ERROR] || [];
                result = {
                    req: req,
                    res: res,
                    swagger: swagger,
                    send: req[init_1.X_SM_PARAMS],
                    receive: {
                        status: res.statusCode || 200
                    }
                };
                _f.label = 1;
            case 1:
                _f.trys.push([1, 4, , 5]);
                bodyType = 'headers' in res ? res.headers['content-type'] : res.getHeader('content-type');
                if (!(typeof bodyType === 'string')) return [3 /*break*/, 3];
                if (!bodyType.match(/json/g)) return [3 /*break*/, 3];
                _a = result;
                _b = [tslib_1.__assign({}, result.receive)];
                _c = {};
                _e = (_d = JSON).parse;
                return [4 /*yield*/, utils_1.getReadableDataAsync(res)];
            case 2:
                _a.receive = tslib_1.__assign.apply(void 0, _b.concat([(_c.body = _e.apply(_d, [_f.sent()]), _c)]));
                _f.label = 3;
            case 3: return [3 /*break*/, 5];
            case 4:
                e_2 = _f.sent();
                error.push("\u63D0\u53D6\u63A5\u53E3\u54CD\u5E94\u51FA\u9519: " + (e_2.message || e_2));
                return [3 /*break*/, 5];
            case 5:
                if (cb) {
                    cb({
                        code: error.length,
                        message: error.join('\n'),
                        result: result
                    });
                }
                delete req[init_1.X_SM_ERROR];
                delete req[init_1.X_SM_PARAMS];
                return [2 /*return*/];
        }
    });
}); }; };
/**
 * @description response
 */
exports.responseMiddleware = createValidateMiddle(exports.responseHooksFactory(validator_1.defaultValidator));
/**
 * @description 劫持 webpackDevServer proxy 配置，以获取参数及相应
 */
function proxyHandle(proxies) {
    return (Array.isArray(proxies) ? proxies : [proxies]).map(function (proxy) {
        var onProxyReq = proxy.onProxyReq, onProxyRes = proxy.onProxyRes;
        return tslib_1.__assign(tslib_1.__assign({}, proxy), { onProxyReq: function (proxyReq, req, res) {
                exports.requestMiddleware(req, res);
                if (onProxyReq) {
                    onProxyReq(proxyReq, req, res);
                }
            }, onProxyRes: function (proxyRes, req, res) {
                exports.responseMiddleware(req, proxyRes);
                if (onProxyRes) {
                    onProxyRes(proxyRes, req, res);
                }
            } });
    });
}
exports.proxyHandle = proxyHandle;
//# sourceMappingURL=middleware.js.map