import { BaseProtocal, ProtocolOptions } from './protocol_base'; import { SendOption, SendSuccess, SendFail } from '@tencent/aegis-core'; import axios from 'axios'; import { SelectorUpdateInfo } from '../selector/selector_base'; export default class HttpProtocal extends BaseProtocal { protected isHttps = false; public constructor(options: ProtocolOptions) { super(options); if (this.protocol === 'https') { this.isHttps = true; } } public async send( options: SendOption, opt: { success?: SendSuccess; fail?: SendFail; bean?: string }, ) { let { url } = options; const [selectorResp, err] = await this.selector.select(url); if (err) { console.error(`[service selector err] ${err.message}`); return; } if (!/^http[s]?:\/\//.test(selectorResp.url || '')) { url = `${this.isHttps ? 'https://' : 'http://'}${selectorResp.url}`; } else { // eslint-disable-next-line prefer-destructuring url = selectorResp.url as string; } // 当 options.addBean !== false 时默认带上 bean 中的参数 if (options.addBean !== false && opt.bean) { url = `${url}${url.indexOf('?') === -1 ? '?' : '&'}${opt.bean}`; } // if (options.method === "post") { // url += `&${options.data}`; // } const startTime = Date.now(); axios({ url, method: 'post', data: options.data, timeout: 3e3, }) .then((res: { data: any }) => { const updateInfo: SelectorUpdateInfo = { success: true, code: 0, cost: Date.now() - startTime, }; this.selector.update(selectorResp.ctx, updateInfo); opt.success?.(JSON.stringify(res.data)); }) .catch((e: any) => { const updateInfo: SelectorUpdateInfo = { success: false, code: -1, cost: Date.now() - startTime, }; this.selector.update(selectorResp.ctx, updateInfo); opt.fail?.(e); console.error(`[aegis server access err] url = ${url}; message = ${e.message}`); }); } }