import {createLogger} from "@gongt/ts-stl-library/debug/create-logger"; import {LOG_LEVEL} from "@gongt/ts-stl-library/debug/levels"; import DI, {DDNames} from "@gongt/ts-stl-library/DI"; import {STATUS_CODE_BASE} from "@gongt/ts-stl-library/request/protocol"; import {RequestError} from "@gongt/ts-stl-library/request/request-error"; import {getRequestTypeName, REQUEST_METHOD} from "@gongt/ts-stl-library/request/request-method"; import {existsSync} from "fs"; import {CoreOptions} from "request"; import {APP_ROOT_PATH} from "../boot/detect-root"; const request = require("request"); const pkgVersion = existsSync(`${APP_ROOT_PATH}/package.json`) ? require(`${APP_ROOT_PATH}/package.json`).version || '?.?.?' : '?.?.?'; const agent = `nodejs:v${process.version} ${process.env.projectName || 'unknown-app'}:v${pkgVersion}`; export interface RequestApiWrap { (method: REQUEST_METHOD, api: string, params?: any, query_params?: any): Promise; } const error = createLogger(LOG_LEVEL.ERROR, 'request'); const debug = createLogger(LOG_LEVEL.DEBUG, 'request'); const data = createLogger(LOG_LEVEL.DATA, 'request'); export function requestWrap(customKey?: string): RequestApiWrap { const key = customKey || DI.get(DDNames.serverRequestKey); return function requestJson(method: REQUEST_METHOD, url: string, params: any = undefined, query_params: any = undefined): Promise { const opt: CoreOptions = { // baseUrl: CONFIG_BASE_DOMAIN, json: true, method: getRequestTypeName(method), headers: { 'X-Server-Key': key, 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': agent, 'Accept': 'application/json', }, maxRedirects: 5, encoding: 'utf-8', timeout: 10000, }; if (params) { params = Object.assign({}, params); } if (query_params) { query_params = Object.assign({}, query_params); } if (method === REQUEST_METHOD.GET) { opt.qs = Object.assign(params, query_params); } else { opt.qs = query_params; opt.body = params; if (typeof params !== 'string') { opt.headers['Content-Type'] = 'application/json; charset=utf8'; } } return new Promise((resolve, reject) => { debug('request to %s:', url); data(opt); request.post(url, opt, (err, res, body) => { return err? reject(err) : resolve(body); }); }).then((s: any) => { debug('request resolved.'); data(s); if (!s) { return Promise.reject(new RequestError(STATUS_CODE_BASE.NO_RESPONSE, 'empty body')); } if (typeof s !== 'object') { return Promise.reject(new RequestError(STATUS_CODE_BASE.UNKNOWN_ERROR, 'response not json')); } if (s.status !== 0) { return Promise.reject(s); } return s; }, (e) => { error(`fail request: ${e.message || e}`); return Promise.reject(e); }); }; }