"use strict";
/**
 * 科拓/统一API通用模块
 * @date 2022-03-04
 * @author 何华东
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.axiosInstance = exports.throwIfResCodeNoSuccess = exports.generateAxiosInstance = exports.defaultUniteApiConfig = exports.ApiResponse = exports.ApiRequestBase = void 0;
var axios_1 = require("axios");
var mslib_1 = require("mslib");
var CryptoUtils_1 = require("./CryptoUtils");
var Contants_1 = require("./Contants");
var Config_1 = require("./Config");
var AxiosUtils_1 = require("./AxiosUtils");
var uuid = require("uuid");
var moment = require('moment');
/**
 * API请求基类
 */
var ApiRequestBase = /** @class */ (function () {
    function ApiRequestBase() {
    }
    return ApiRequestBase;
}());
exports.ApiRequestBase = ApiRequestBase;
/**
 * API响应类
 */
var ApiResponse = /** @class */ (function () {
    function ApiResponse(resCode) {
        this.resCode = resCode;
    }
    /**
     * 判断指定的响应码是否为成功响应码
     * @param resCode 指定的响应码
     * @returns
     */
    ApiResponse.resCodeIsSuccess = function (resCode) {
        return (resCode === null || resCode === void 0 ? void 0 : resCode.toString()) === '0';
    };
    /**
     * 创建一个失败响应对象
     * @param resMsg 失败信息
     * @returns
     */
    ApiResponse.failed = function (resMsg) {
        var apiResponse = new ApiResponse('-1');
        apiResponse.resMsg = resMsg;
        return apiResponse;
    };
    /**
     * 创建一个成功响应对象
     * @param data 数据
     * @returns
     */
    ApiResponse.successWithData = function (data) {
        var apiResponse = new ApiResponse('0');
        apiResponse.data = data;
        return apiResponse;
    };
    /**
     * 创建一个成功响应对象
     * @param resMsg 信息
     * @returns
     */
    ApiResponse.successWithMsg = function (resMsg) {
        var apiResponse = new ApiResponse('0');
        apiResponse.resMsg = resMsg;
        return apiResponse;
    };
    /**
     * 成功响应对象
     */
    ApiResponse.success = new ApiResponse('0');
    return ApiResponse;
}());
exports.ApiResponse = ApiResponse;
/**
 * 统一API默认配置
 */
exports.defaultUniteApiConfig = {
    baseUrl: Contants_1.Contants.UNITE_API_BASE_URL,
    timeout: 10000,
    appId: null,
    appSecret: null,
    axiosErrorHandler: function (error) {
        if (error.isAxiosError)
            throw AxiosUtils_1.generateApiErrorFromAxiosError(error);
        throw error;
    }
};
/**
 * 生成统一API axios实例
 *
 * 默认会对请求进行拦截，自动填充默认请求参数(appId、ts等)，并签名
 *
 * 默认会对响应进行拦截，进行日志记录
 * @type { UniteApiConfig } 用户需实现UniteApiConfig接口，并在ioc中注册
 * @returns
 */
function generateAxiosInstance(uniteApiConfig) {
    var axiosInstance = axios_1.default.create({
        baseURL: uniteApiConfig.baseUrl,
        timeout: uniteApiConfig.timeout,
    });
    axiosInstance.interceptors.request.use(function (config) {
        var _a;
        config.headers = Object.assign(config.headers, {
            'Content-Type': 'application/json;charset=utf-8',
            'version': ((_a = config.headers) === null || _a === void 0 ? void 0 : _a.version) || '1.0.0',
        });
        var dataWrap = {
            appId: uniteApiConfig.appId,
            reqId: "" + uuid.v4().replace('-', ''),
            ts: "" + moment().valueOf(),
            key: ''
        };
        dataWrap = Object.assign(dataWrap, config.data);
        var signStr = Object.keys(dataWrap).sort().filter(function (k) {
            if (['appId', 'key'].includes(k))
                return false;
            if (dataWrap[k] === undefined || dataWrap[k] === null || dataWrap[k] === '')
                return false;
            if (typeof dataWrap[k] === 'object')
                return false;
            if (Array.isArray(dataWrap[k]))
                return false;
            return true;
        }).map(function (k) { return k + "=" + dataWrap[k]; }).join('&') + ("&" + uniteApiConfig.appSecret);
        dataWrap.key = CryptoUtils_1.CryptoUtils.md5(signStr).toUpperCase();
        config.data = dataWrap;
        return config;
    }, function (error) {
        return uniteApiConfig.axiosErrorHandler(error);
    });
    axiosInstance.interceptors.response.use(function (response) {
        //生产环境不记录SQL代理日志
        if (Contants_1.Contants.IS_PROD && response.config.url.includes('/dbproxy/'))
            return response;
        mslib_1.logger.info("\u7EDF\u4E00API'" + response.config.url + "'\u8C03\u7528\u6210\u529F,\n                    requestUrl:" + (response.config.baseURL + response.config.url) + ",\n                    headers:" + JSON.stringify(response.config.headers) + ",\n                    requestData:" + response.config.data + ",\n                    response:" + JSON.stringify(response.data));
        return response;
    }, function (error) {
        return uniteApiConfig.axiosErrorHandler(error);
    });
    return axiosInstance;
}
exports.generateAxiosInstance = generateAxiosInstance;
/**
 * 判断指定的统一API响应报文中的响应码是否为非成功，如果非成功则抛出ApiError异常
 * @param axiosResponse 指定的统一API响应报文
 */
function throwIfResCodeNoSuccess(axiosResponse) {
    var _a;
    if (!ApiResponse.resCodeIsSuccess((_a = axiosResponse.data) === null || _a === void 0 ? void 0 : _a.resCode)) {
        throw AxiosUtils_1.generateApiErrorFromAxiosResponse(axiosResponse, '统一API返回错误');
    }
}
exports.throwIfResCodeNoSuccess = throwIfResCodeNoSuccess;
mslib_1.logger.info("getUniteApiConfig:" + JSON.stringify(Config_1.getUniteApiConfig()));
mslib_1.logger.info("CONFIG:" + JSON.stringify(Object.assign(exports.defaultUniteApiConfig, Config_1.getUniteApiConfig())));
/**
 * 统一API axios实例
 */
exports.axiosInstance = generateAxiosInstance(Object.assign(exports.defaultUniteApiConfig, Config_1.getUniteApiConfig()));
//# sourceMappingURL=KTApiCommon.js.map