1851320
阅读腾讯出的SDK的源码,发现以下代码(删掉了注释)
const TencentCloudSDKHttpException = require("./exception/tencent_cloud_sdk_exception");
const crypto = require('crypto');
class Sign {
static sign(secretKey, signStr, signMethod) {
let signMethodMap = {
HmacSHA1: "sha1",
HmacSHA256: "sha256"
};
if (!signMethodMap.hasOwnProperty(signMethod)) {
throw new TencentCloudSDKHttpException("signMethod invalid, signMethod only support (HmacSHA1, HmacSHA256)");
}
let hmac = crypto.createHmac(signMethodMap[signMethod], secretKey || "");
return hmac.update(new Buffer(signStr, 'utf8')).digest('base64')
}
}
module.exports = Sign;
忽略其中使用废弃的的new Buffer不管, 这本身只是在提供一个函数,根本不需要实例化,为什么非要用class,这算不算滥用class
我的理解是这样写
const TencentCloudSDKHttpException = require("./exception/tencent_cloud_sdk_exception");
const crypto = require('crypto');
function sign(secretKey, signStr, signMethod) {
let signMethodMap = {
HmacSHA1: "sha1",
HmacSHA256: "sha256"
};
if (!signMethodMap.hasOwnProperty(signMethod)) {
throw new TencentCloudSDKHttpException("signMethod invalid, signMethod only support (HmacSHA1, HmacSHA256)");
}
let hmac = crypto.createHmac(signMethodMap[signMethod], secretKey || "");
return hmac.update(Buffer.from(signStr, 'utf8')).digest('base64')
}
module.exports = Sign;
或者保持原代码的调用方式,这样写
const TencentCloudSDKHttpException = require("./exception/tencent_cloud_sdk_exception");
const crypto = require('crypto');
module.exports = {
sign(secretKey, signStr, signMethod) {
let signMethodMap = {
HmacSHA1: "sha1",
HmacSHA256: "sha256"
};
if (!signMethodMap.hasOwnProperty(signMethod)) {
throw new TencentCloudSDKHttpException("signMethod invalid, signMethod only support (HmacSHA1, HmacSHA256)");
}
let hmac = crypto.createHmac(signMethodMap[signMethod], secretKey || "");
return hmac.update(Buffer.from(signStr, 'utf8')).digest('base64')
}
};