优化sdk-nodejs以下功能:

1、新增同步请求方式(executeSync、executeTokenSync);
2、优化请求异常中断问题,返回502错误码;
3、优化签名方法;
This commit is contained in:
Changeden
2021-04-12 15:42:52 +08:00
parent 472942e93e
commit e1b860c75a
8 changed files with 146 additions and 147 deletions

View File

@@ -70,7 +70,7 @@ exports.Class = (function () {
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function (name, fn) {
prototype[name] = typeof prop[name] == 'function' && typeof _super[name] == 'function' && fnTest.test(prop[name]) ? (function (name, fn) {
return function () {
var tmp = this._super;
@@ -107,7 +107,6 @@ exports.Class = (function () {
};// ------Class Creation end------
return {
/**
* 创建一个类

View File

@@ -1,22 +1,22 @@
const needle = require('needle')
const moment = require('moment')
const needle = require('needle');
const moment = require('moment');
const {Class} = require("./Class");
const {RequestType} = require('./RequestType')
const {SignUtil} = require('./SignUtil')
const {BaseRequest} = require('../request/BaseRequest')
const {Class} = require('./Class');
const {RequestType} = require('./RequestType');
const {SignUtil} = require('./SignUtil');
const {BaseRequest} = require('../request/BaseRequest');
const HEADERS = {'Accept-Encoding': 'identity'}
const HEADERS = {'Accept-Encoding': 'identity'};
const getHeaders = function (headers) {
if (!headers) {
return HEADERS
return HEADERS;
}
for (const key in HEADERS) {
headers[key] = HEADERS[key];
}
return headers
}
return headers;
};
const OpenClient = Class.create({
/**
@@ -36,11 +36,11 @@ const OpenClient = Class.create({
* @param callback 回调函数参数jsonundefined则使用executeSync
*/
execute: function (request, callback) {
if (typeof callback == 'function') {
this.executeToken(request, null, callback)
} else {
return this.executeSync(request)
}
if (typeof callback == 'function') {
this.executeToken(request, null, callback);
} else {
return this.executeSync(request);
}
},
/**
* 发送同步请求
@@ -49,9 +49,9 @@ const OpenClient = Class.create({
executeSync: function (request) {
return new Promise((resolve) => {
this.execute(request, res => {
resolve(res)
})
})
resolve(res);
});
});
},
/**
* 发送请求
@@ -61,7 +61,7 @@ const OpenClient = Class.create({
*/
executeToken: function (request, token, callback) {
if (!(request instanceof BaseRequest)) {
throw 'request类未继承BaseRequest'
throw 'request类未继承BaseRequest';
}
if (typeof callback == 'function') {
const requestType = request.getRequestType();
@@ -71,85 +71,85 @@ const OpenClient = Class.create({
switch (requestType) {
case RequestType.GET:
this._get(request, callback);
break
break;
case RequestType.POST_FORM:
this._postForm(request, callback);
break
break;
case RequestType.POST_JSON:
this._postJson(request, callback);
break
break;
case RequestType.POST_FILE:
this._postFile(request, callback);
break
break;
default : {
throw 'request.getRequestType()类型不正确'
throw 'request.getRequestType()类型不正确';
}
}
}
} else {
return this.executeTokenSync(request, token)
return this.executeTokenSync(request, token);
}
},
/**
* 发送同步请求
* @param request 请求类
* @param token token
*/
/**
* 发送同步请求
* @param request 请求类
* @param token token
*/
executeTokenSync: function (request, token) {
return new Promise((resolve) => {
this.executeToken(request, token, res => {
resolve(res)
})
})
return new Promise((resolve) => {
this.executeToken(request, token, res => {
resolve(res);
});
});
},
_get: function(request, callback) {
const allParams = this._buildParams(request)
const that = this
_get: function (request, callback) {
const allParams = this._buildParams(request);
const that = this;
// needle.request(method, url, data[, options][, callback])
needle.request('GET',this.url, allParams, {
needle.request('GET', this.url, allParams, {
headers: getHeaders()
}, function(error, response) {
callback(that._parseResponse(error, response, request))
}, function (error, response) {
callback(that._parseResponse(error, response, request));
});
},
_postForm: function (request, callback) {
const allParams = this._buildParams(request)
const that = this
needle.request('POST',this.url, allParams, {
const allParams = this._buildParams(request);
const that = this;
needle.request('POST', this.url, allParams, {
headers: getHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
}, function(error, response) {
callback(that._parseResponse(error, response, request))
}, function (error, response) {
callback(that._parseResponse(error, response, request));
});
},
_postJson: function (request, callback) {
const allParams = this._buildParams(request)
const that = this
needle.request('POST',this.url, allParams, {
const allParams = this._buildParams(request);
const that = this;
needle.request('POST', this.url, allParams, {
headers: getHeaders(), json: true
}, function(error, response) {
callback(that._parseResponse(error, response, request))
}, function (error, response) {
callback(that._parseResponse(error, response, request));
});
},
_postFile: function (request, callback) {
const allParams = this._buildParams(request)
const allParams = this._buildParams(request);
const files = request.files;
files.forEach(row => {
// 设置成{ file: row.path, content_type: 'application/octet-stream' }格式
// needle会认为是上传文件
allParams[row.name] = { file: row.path, content_type: 'application/octet-stream' }
})
const that = this
needle.request('POST',this.url, allParams, {
allParams[row.name] = {file: row.path, content_type: 'application/octet-stream'};
});
const that = this;
needle.request('POST', this.url, allParams, {
headers: getHeaders(), multipart: true
}, function(error, response) {
callback(that._parseResponse(error, response, request))
}, function (error, response) {
callback(that._parseResponse(error, response, request));
});
},
_parseResponse: function (error, response, request) {
if (!error && response.statusCode === 200) {
return request.parseResponse(response.body)
return request.parseResponse(response.body);
} else {
// throw '请求异常:' + error
return { // 重新封装请求异常回调,以防中断
@@ -157,7 +157,7 @@ const OpenClient = Class.create({
code: '502',
sub_msg: `${error}`,
sub_code: 'isv.invalid-server'
}
};
}
},
_buildParams: function (request, token) {
@@ -169,16 +169,16 @@ const OpenClient = Class.create({
'timestamp': moment().format('YYYY-MM-DD HH:mm:ss'),
'version': request.getVersion(),
'biz_content': JSON.stringify(request.bizModel)
}
};
if (token) {
allParams['app_auth_token'] = token
allParams['app_auth_token'] = token;
}
// 创建签名
const sign = SignUtil.createSign(allParams, this.privateKey, 'RSA2')
allParams.sign = sign
const sign = SignUtil.createSign(allParams, this.privateKey, 'RSA2');
allParams.sign = sign;
return allParams;
}
})
});
module.exports = OpenClient
module.exports = OpenClient;

View File

@@ -3,4 +3,4 @@ exports.RequestType = {
POST_FORM: 'POST_FORM',
POST_JSON: 'POST_JSON',
POST_FILE: 'POST_FILE'
}
};

View File

@@ -1,12 +1,12 @@
const {KJUR, hextob64} = require('jsrsasign')
const {KJUR, hextob64} = require('jsrsasign');
const HashMap = {
SHA256withRSA: 'SHA256withRSA',
SHA1withRSA: 'SHA1withRSA'
}
};
const PEM_BEGIN = '-----BEGIN PRIVATE KEY-----\n'
const PEM_END = '\n-----END PRIVATE KEY-----'
const PEM_BEGIN = '-----BEGIN PRIVATE KEY-----\n';
const PEM_END = '\n-----END PRIVATE KEY-----';
/**
* rsa签名参考https://www.jianshu.com/p/145eab95322c
@@ -20,16 +20,16 @@ exports.SignUtil = {
* @returns 返回签名内容
*/
createSign(params, privateKey, signType) {
const content = this.getSignContent(params)
return this.sign(content, privateKey, signType)
const content = this.getSignContent(params);
return this.sign(content, privateKey, signType);
},
sign: function (content, privateKey, signType) {
if (signType.toUpperCase() === 'RSA') {
return this.rsaSign(content, privateKey, HashMap.SHA1withRSA)
return this.rsaSign(content, privateKey, HashMap.SHA1withRSA);
} else if (signType.toUpperCase() === 'RSA2') {
return this.rsaSign(content, privateKey, HashMap.SHA256withRSA)
return this.rsaSign(content, privateKey, HashMap.SHA256withRSA);
} else {
throw 'signType错误'
throw 'signType错误';
}
},
/**
@@ -40,26 +40,26 @@ exports.SignUtil = {
* @returns 返回签名字符串base64
*/
rsaSign: function (content, privateKey, hash) {
privateKey = this._formatKey(privateKey)
privateKey = this._formatKey(privateKey);
// 创建 Signature 对象
const signature = new KJUR.crypto.Signature({
alg: hash,
//!这里指定 私钥 pem!
prvkeypem: privateKey
})
signature.updateString(content)
const signData = signature.sign()
});
signature.updateString(content);
const signData = signature.sign();
// 将内容转成base64
return hextob64(signData)
return hextob64(signData);
},
_formatKey: function (key) {
if (!key.startsWith(PEM_BEGIN)) {
key = PEM_BEGIN + key
key = PEM_BEGIN + key;
}
if (!key.endsWith(PEM_END)) {
key = key + PEM_END
key = key + PEM_END;
}
return key
return key;
},
/**
* 获取签名内容
@@ -67,23 +67,23 @@ exports.SignUtil = {
* @returns {string}
*/
getSignContent: function (params) {
const paramNames = []
const paramNames = [];
// 获取对象中的Key
paramNames.push(...Object.keys(params || {})
// 过滤无效的KeyValue
.filter(paramName => {
// 参数名不为undefined且参数值不为undefined
return !(typeof paramName === undefined || typeof params[paramName] === undefined)
}))
// 过滤无效的KeyValue
.filter(paramName => {
// 参数名不为undefined且参数值不为undefined
return !(typeof paramName === undefined || typeof params[paramName] === undefined);
}));
paramNames.sort()
paramNames.sort();
// 合成签名字符串
const paramNameValue = paramNames.map(paramName => {
const val = params[paramName];
return `${paramName}=${val}`
})
return `${paramName}=${val}`;
});
return paramNameValue.join('&')
return paramNameValue.join('&');
}
}
};