UNPKG

rapid-swiftpass

Version:

SwiftPass module

72 lines (65 loc) 2.31 kB
/** * Copyright (c) 2017 Lucky Byte, Inc. */ const debug = require('debug')('swiftpass'); const winston = require('winston'); const request = require('request-promise-native'); const xml2js = require('xml2js'); /** * 发送请求 * * 参数: * dest_url: 目标地址 * reqt_json: 请求报文,JSON 对象 * options: 其他参数,JSON 对象(可选的),可用的值包括: * * timeout: 超时时间,毫秒为单位(10-60),默认 20 * * retry: 超时重试次数(0-10),默认 3 * 返回 * 响应数据 */ const post = async (dest_url, reqt_json, options) => { if (!dest_url || !reqt_json) { throw new Error('[post]参数无效'); } let retry = 3; let timeout = 20000; if (options) { if (options.retry >= 0 && options.retry <= 10) { retry = options.retry; } else { winston.warn(`[post]参数[retry][${options.retry}]不在[0-10]之间`); } if (options.timeout > 10 && options.timeout <= 60) { timeout = options.timeout * 1000; } else { winston.warn(`[post]参数[timeout][${options.timeout}]不在[10-60]之间`); } } const xml_data = new xml2js.Builder({ rootName: 'xml', renderOpts: false, headless: true, }).buildObject(reqt_json); for (let i = 0; i < retry; i++) { try { debug(`发送威富通请求到[${dest_url}],retry=${retry}, timeout=${timeout}`); return await request.post({ headers: { 'user-agent': 'lucky-https/4.1', 'content-type': 'text/plain; charset=UTF-8', }, url: dest_url, timeout: timeout, encoding: 'utf-8', body: xml_data, }); } catch (err) { // 对于连接超时的情况重试,读取超时的情况不重试,以避免重复交易 if (err.name == 'RequestError' && err.cause && err.cause.code == 'ETIMEDOUT' && err.cause.connect) { debug(`连接服务器超时,尝试重新连接[${i+1}] ...`); continue; } throw err; } } } module.exports = post;