|
|
|
/**
|
|
|
|
* 公用方法
|
|
|
|
*/
|
|
|
|
|
|
|
|
import fs from 'node:fs';
|
|
|
|
import { readdir, readFile } from 'node:fs/promises';
|
|
|
|
import { resolve } from 'node:path';
|
|
|
|
import md5 from 'md5';
|
|
|
|
|
|
|
|
class Common {
|
|
|
|
|
|
|
|
//构造函数,设置默认配置
|
|
|
|
constructor() {
|
|
|
|
this.configDir = resolve('conf/');
|
|
|
|
}
|
|
|
|
|
|
|
|
getTimestamp() {
|
|
|
|
return Math.floor(Date.now());
|
|
|
|
}
|
|
|
|
|
|
|
|
getTimestampInSeconds() {
|
|
|
|
return Math.floor(Date.now() / 1000);
|
|
|
|
}
|
|
|
|
|
|
|
|
sortDict(obj) { //dict按key排序
|
|
|
|
return Object.keys(obj).sort().reduce(function (result, key) {
|
|
|
|
result[key] = obj[key];
|
|
|
|
return result;
|
|
|
|
}, {});
|
|
|
|
}
|
|
|
|
|
|
|
|
joinDict(obj, glue, separator) { //dict拼接成字符串
|
|
|
|
if (typeof(glue) == 'undefined') {
|
|
|
|
glue = '=';
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof(separator) == 'undefined') {
|
|
|
|
separator = '&';
|
|
|
|
}
|
|
|
|
|
|
|
|
return Object.keys(obj).map(function(key) {
|
|
|
|
let arr = [key];
|
|
|
|
let val = obj[key];
|
|
|
|
if (typeof(val) == 'string' || typeof(val) == 'number') {
|
|
|
|
arr.push(val);
|
|
|
|
}else if (typeof(val) == 'object') {
|
|
|
|
arr.push(JSON.stringify(val));
|
|
|
|
}
|
|
|
|
|
|
|
|
return arr.join(glue);
|
|
|
|
}).join(separator);
|
|
|
|
}
|
|
|
|
|
|
|
|
sign(params, token) { //对参数做MD5签名
|
|
|
|
return md5( JSON.stringify(this.sortDict(params)) + token );
|
|
|
|
}
|
|
|
|
|
|
|
|
//从conf/目录读取配置文件内容
|
|
|
|
async getConfigFromJsonFile(filename) {
|
|
|
|
let data = null;
|
|
|
|
|
|
|
|
let filePath = this.configDir + `/${filename}`;
|
|
|
|
if (fs.existsSync(filePath)) {
|
|
|
|
try {
|
|
|
|
const contents = await readFile(filePath, { encoding: 'utf8' });
|
|
|
|
if (contents) {
|
|
|
|
data = JSON.parse(contents);
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
console.error(`[FAILED] get config content from %s failed, error: %s`, filePath, err.message);
|
|
|
|
}
|
|
|
|
}else {
|
|
|
|
console.error("[ERROR] file %s not exist.", filePath);
|
|
|
|
}
|
|
|
|
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
let commonFuns = new Common();
|
|
|
|
export default commonFuns;
|