优化sdk-nodejs以下功能:

1、新增同步请求方式(executeSync、executeTokenSync);
2、优化请求异常中断问题,返回502错误码;
3、优化签名方法;
pull/11/head
Changeden 4 years ago
parent 472942e93e
commit e1b860c75a
  1. 3
      sop-sdk/sdk-nodejs/common/Class.js
  2. 94
      sop-sdk/sdk-nodejs/common/OpenClient.js
  3. 2
      sop-sdk/sdk-nodejs/common/RequestType.js
  4. 50
      sop-sdk/sdk-nodejs/common/SignUtil.js
  5. 38
      sop-sdk/sdk-nodejs/main.js
  6. 12
      sop-sdk/sdk-nodejs/request/BaseRequest.js
  7. 16
      sop-sdk/sdk-nodejs/request/StoryGetRequest.js
  8. 8
      sop-sdk/sdk-nodejs/testClass.js

@ -70,7 +70,7 @@ exports.Class = (function () {
// Copy the properties over onto the new prototype // Copy the properties over onto the new prototype
for (var name in prop) { for (var name in prop) {
// Check if we're overwriting an existing function // 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 () { return function () {
var tmp = this._super; var tmp = this._super;
@ -107,7 +107,6 @@ exports.Class = (function () {
};// ------Class Creation end------ };// ------Class Creation end------
return { return {
/** /**
* 创建一个类 * 创建一个类

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

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

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

@ -1,26 +1,26 @@
const OpenClient = require('./common/OpenClient') const OpenClient = require('./common/OpenClient');
const {StoryGetRequest} = require('./request/StoryGetRequest') const {StoryGetRequest} = require('./request/StoryGetRequest');
// 应用ID // 应用ID
const appId = '2019032617262200001' const appId = '2019032617262200001';
// 应用私钥,2048位,PKCS8 // 应用私钥,2048位,PKCS8
const privateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCXJv1pQFqWNA/++OYEV7WYXwexZK/J8LY1OWlP9X0T6wHFOvxNKRvMkJ5544SbgsJpVcvRDPrcxmhPbi/sAhdO4x2PiPKIz9Yni2OtYCCeaiE056B+e1O2jXoLeXbfi9fPivJZkxH/tb4xfLkH3bA8ZAQnQsoXA0SguykMRZntF0TndUfvDrLqwhlR8r5iRdZLB6F8o8qXH6UPDfNEnf/K8wX5T4EB1b8x8QJ7Ua4GcIUqeUxGHdQpzNbJdaQvoi06lgccmL+PHzminkFYON7alj1CjDN833j7QMHdPtS9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9i6ccMjAyTR2qfLkxv0hlbBbsPHz4BbU63xhTJp3Ghi0/ey/1HQKBgQC2VsgqC6ykfSidZUNLmQZe3J0p/Qf9VLkfrQ+xaHapOs6AzDU2H2osuysqXTLJHsGfrwVaTs00ER2z8ljTJPBUtNtOLrwNRlvgdnzyVAKHfOgDBGwJgiwpeE9voB1oAV/mXqSaUWNnuwlOIhvQEBwekqNyWvhLqC7nCAIhj3yvNQKBgQCqYbeec56LAhWP903Zwcj9VvG7sESqXUhIkUqoOkuIBTWFFIm54QLTA1tJxDQGb98heoCIWf5x/A3xNI98RsqNBX5JON6qNWjb7/dobitti3t99v/ptDp9u8JTMC7penoryLKK0Ty3bkan95Kn9SC42YxaSghzqkt+uvfVQgiNGQKBgGxU6P2aDAt6VNwWosHSe+d2WWXt8IZBhO9d6dn0f7ORvcjmCqNKTNGgrkewMZEuVcliueJquR47IROdY8qmwqcBAN7Vg2K7r7CPlTKAWTRYMJxCT1Hi5gwJb+CZF3+IeYqsJk2NF2s0w5WJTE70k1BSvQsfIzAIDz2yE1oPHvwVAoGAA6e+xQkVH4fMEph55RJIZ5goI4Y76BSvt2N5OKZKd4HtaV+eIhM3SDsVYRLIm9ZquJHMiZQGyUGnsvrKL6AAVNK7eQZCRDk9KQz+0GKOGqku0nOZjUbAu6A2/vtXAaAuFSFx1rUQVVjFulLexkXR3KcztL1Qu2k5pB6Si0K/uwQ=';
// 接口url // 接口url
const url = 'http://localhost:8081' const url = 'http://localhost:8081';
// 创建客户端 // 创建客户端
const openClient = new OpenClient(appId, privateKey, url) const openClient = new OpenClient(appId, privateKey, url);
function test() { function test() {
// 创建请求 // 创建请求
const request = new StoryGetRequest() const request = new StoryGetRequest();
// 设置业务参数 // 设置业务参数
request.bizModel = { request.bizModel = {
id: 111, id: 111,
name: 'jim' name: 'jim'
} };
// 添加上传文件 // 添加上传文件
// request.files = [ // request.files = [
@ -30,41 +30,41 @@ function test() {
// ] // ]
openClient.execute(request, data => { openClient.execute(request, data => {
console.log('异步请求') console.log('异步请求');
// 成功 // 成功
if (!data.sub_code) { if (!data.sub_code) {
console.log('成功', data); console.log('成功', data);
} else { } else {
console.error('失败', data) console.error('失败', data);
} }
}) });
// 使用Promise进行封装 // 使用Promise进行封装
openClient.executeSync(request).then(data => { openClient.executeSync(request).then(data => {
console.log('同步请求-Promise') console.log('同步请求-Promise');
// 成功 // 成功
if (!data.sub_code) { if (!data.sub_code) {
console.log('成功', data); console.log('成功', data);
} else { } else {
console.error('失败', data) console.error('失败', data);
} }
}) });
// 使用Async/Await进行封装 // 使用Async/Await进行封装
async function syncRequest() { async function syncRequest() {
const data = await openClient.execute(request) const data = await openClient.execute(request);
console.log('同步请求-Async/Await') console.log('同步请求-Async/Await');
// 成功 // 成功
if (!data.sub_code) { if (!data.sub_code) {
console.log('成功', data); console.log('成功', data);
} else { } else {
console.error('失败', data) console.error('失败', data);
} }
} }
syncRequest() syncRequest();
} }
test() test();

@ -1,18 +1,18 @@
const {Class} = require("../common/Class"); const {Class} = require('../common/Class');
/** /**
* 请求类父类 * 请求类父类
*/ */
exports.BaseRequest = Class.create({ exports.BaseRequest = Class.create({
init: function () { init: function () {
this.bizModel = {} this.bizModel = {};
/* /*
[ [
{name: 'file1', path: 'd:/dd/1.txt'}, {name: 'file1', path: 'd:/dd/1.txt'},
{name: 'file2', path: 'd:/dd/2.txt'} {name: 'file2', path: 'd:/dd/2.txt'}
] ]
*/ */
this.files = [] this.files = [];
}, },
/** /**
* 返回接口名称 * 返回接口名称
@ -40,9 +40,9 @@ exports.BaseRequest = Class.create({
parseResponse: function (responseData) { parseResponse: function (responseData) {
let data = responseData['error_response']; let data = responseData['error_response'];
if (!data) { if (!data) {
const dataNodeName = this.getMethod().replace(/\./g, '_') + '_response' const dataNodeName = this.getMethod().replace(/\./g, '_') + '_response';
data = responseData[dataNodeName] data = responseData[dataNodeName];
} }
return data; return data;
} }
}) });

@ -1,6 +1,6 @@
const {Class} = require("../common/Class"); const {Class} = require('../common/Class');
const {RequestType} = require("../common/RequestType"); const {RequestType} = require('../common/RequestType');
const {BaseRequest} = require('./BaseRequest') const {BaseRequest} = require('./BaseRequest');
/** /**
* 创建一个请求类继承BaseRequest重写三个函数 * 创建一个请求类继承BaseRequest重写三个函数
@ -8,15 +8,15 @@ const {BaseRequest} = require('./BaseRequest')
const StoryGetRequest = Class.create({ const StoryGetRequest = Class.create({
getMethod: function () { getMethod: function () {
return "story.get" return 'story.get';
}, },
getVersion: function () { getVersion: function () {
return "1.0" return '1.0';
}, },
getRequestType: function () { getRequestType: function () {
return RequestType.GET return RequestType.GET;
} }
}, BaseRequest) // 继承BaseRequest }, BaseRequest); // 继承BaseRequest
module.exports.StoryGetRequest = StoryGetRequest module.exports.StoryGetRequest = StoryGetRequest;

@ -3,7 +3,7 @@
* 运行node testClass.js * 运行node testClass.js
*/ */
const {Class} = require('./common/Class') const {Class} = require('./common/Class');
function testClass() { function testClass() {
//------------------------- //-------------------------
@ -24,7 +24,7 @@ function testClass() {
// 声明类实例 // 声明类实例
var Jim = new Person({name: 'Jim'}); var Jim = new Person({name: 'Jim'});
console.log('Jim name:' + Jim.getName()) console.log('Jim name:' + Jim.getName());
//例子2:------------------------- //例子2:-------------------------
@ -43,10 +43,10 @@ function testClass() {
}, Person); }, Person);
var man = new Man({name: 'Tom', age: 22}); var man = new Man({name: 'Tom', age: 22});
console.log('man name:' + man.getName()) console.log('man name:' + man.getName());
console.log('Jim instanceof Person: ' + (Jim instanceof Person)); console.log('Jim instanceof Person: ' + (Jim instanceof Person));
console.log('man instanceof Person: ' + (man instanceof Person)); console.log('man instanceof Person: ' + (man instanceof Person));
} }
testClass() testClass();

Loading…
Cancel
Save