-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
115 lines (92 loc) · 2.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/**
* User: ngnono
* Date: 16-4-6
* Time: 下午5:51
* To change this template use File | Settings | File Templates.
*/
'use strict';
var util = require('util');
var url = require('url');
var md5 = require('md5');
var qs = require('qs');
var debug = require('debug')('ngnono:webClient-g');
var Sdk = require('./lib/sdk');
const headerName = {
consumerKeyName: 'X-ConsumerKey',
signName: 'X-Sign'
};
function GsbClient(settings, routes) {
Sdk.call(this, settings, routes);
this.use(_signSdkMiddleware);
}
util.inherits(GsbClient, Sdk);
/**
* 签名中间件
* @param options
* @param done
* @private
*/
function _signSdkMiddleware(options, done) {
debug(JSON.stringify(options));
options = _verifyOptions(options);
let method = options.requestOptions.method.toUpperCase();
let u = url.parse(options.requestOptions.uri);
let pathAndQuery = u.path || '';
let q = null;
let qsArr = [];
qsArr.push(pathAndQuery);
if (options.requestOptions.qs) {
q = qs.stringify(options.requestOptions.qs, {encode: false}) || null;
if(u.search){
qsArr.push('&')
} else{
qsArr.push('?');
}
qsArr.push(q);
}
let body;
switch (method) {
case 'PATCH':
case 'POST':
case 'PUT':
body = JSON.stringify(options.requestOptions.body) || '';
break;
default :
body = '';
break;
}
let consumerKey = options.settings.consumerKey || '';
let secretKey = options.settings.secretKey || '';
let vals = [
method,
qsArr.join(''),
body,
consumerKey,
secretKey
];
let signBefore = vals.join('').toUpperCase();
debug('signBefore:%s', signBefore);
let sign = md5(signBefore);
debug('sign:%s', sign);
options.requestOptions.headers[headerName.consumerKeyName] = consumerKey;
options.requestOptions.headers[headerName.signName] = sign;
done(null, options);
}
/**
* 验证 options
* @param options
* @returns {*|{}}
* @private
*/
function _verifyOptions(options) {
options = options || {};
options.requestOptions = options.requestOptions || {};
options.settings = options.settings || {};
options.requestOptions.headers = options.requestOptions.headers || {};
return options;
}
/**
* GSB WEB API client
* @type {GsbClient}
*/
module.exports = GsbClient;