imsdk-server-core
Version:
轻量级Web服务器框架、WebSocket服务器框架。采用Typescript编写,简单易用。
248 lines (247 loc) • 8.82 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnvContext = void 0;
/**
* 运行环境工具类
* lo4js相关信息:https://log4js-node.github.io/log4js-node/
* 自定义证书生成:
* openssl genrsa -out localhost.key 2048
* openssl req -new -sha256 -key localhost.key -out localhost.csr
* openssl x509 -req -in localhost.csr -signkey localhost.key -out localhost.pem
*/
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const log4js_1 = __importDefault(require("log4js"));
const crypto_js_1 = __importDefault(require("crypto-js"));
class EnvContext {
/**
* @param appDir 节点启动时指定的一个根目录绝对路径
* @param appEnv 节点启动环境类型,如: development、production1、production2、production3...
* @param appName 节点类型名称,如 http、home、chat...
* @param appHost 节点所在主机名
* @param appInIP 节点所在主机内网IP
* @param appPort 节点所监听的端口号
* @param appSSLs 节点SSL证书路径
* @param appLinks 本节点需要连接的其它节点类型名称
* @param appNodes 全部的节点
* @param encode 编码默认值为utf8
*/
constructor(appDir, appEnv, appName, appHost, appInIP, appPort, appSSLs, appLinks, appNodes, encode = 'utf8') {
this._appDir = appDir;
this._appEnv = appEnv;
this._appName = appName;
this._appHost = appHost;
this._appInIP = appInIP;
this._appPort = Number(appPort);
this._appSSLs = appSSLs;
this._appLinks = appLinks;
this._appNodes = appNodes;
this._encode = encode;
this._logcfgs = null;
this._context = {};
}
/**
* 加载对应_envName的log4js配置信息,并初始化log4js
* @param configs log4js配置的文件绝对路径 或 log4js配置的数据内容
*/
initLog4js(configs) {
let logStr = typeof configs === 'string' ? fs_1.default.readFileSync(configs, { encoding: this._encode }) : JSON.stringify(configs);
logStr = logStr.replace(new RegExp('\\${opt:appDir}', 'gm'), this._appDir);
logStr = logStr.replace(new RegExp('\\${opt:appEnv}', 'gm'), this._appEnv);
logStr = logStr.replace(new RegExp('\\${opt:appName}', 'gm'), this._appName);
logStr = logStr.replace(new RegExp('\\${opt:appHost}', 'gm'), this._appHost);
logStr = logStr.replace(new RegExp('\\${opt:appPort}', 'gm'), String(this._appPort));
this._logcfgs = JSON.parse(logStr)[this._appEnv];
log4js_1.default.configure(this._logcfgs);
}
/**
* 加载对应_envName的自定义配置信息
* @param configs 自定义配置的文件绝对路径 或 自定义配置的数据内容
*/
loadConfig(configs) {
if (typeof configs === 'string') {
const cfgStr = fs_1.default.readFileSync(configs, { encoding: this._encode });
return JSON.parse(cfgStr)[this._appEnv];
}
else {
return configs[this._appEnv];
}
}
/**
* 指定环境、指定进程进行定制化回掉
* @param appEnv 指定进程启动环境类型,支持多个环境,如:development|production
* @param appName 指定进程类型,支持多个名称,如:gate|home|chat,传null表示全部环境
* @param callback 在这个回调函数里面定制自己的逻辑
*/
configure(appEnv, appName, callback) {
const envArr = appEnv.split('|');
if (envArr.indexOf(this._appEnv) >= 0) {
if (appName) {
const appArr = appName.split('|');
if (appArr.indexOf(this._appName) >= 0) {
callback();
}
}
else {
callback();
}
}
}
/**
* 获取一个log4js实例
* @param category log4js的category
*/
getLogger(category) {
if (!this._logcfgs)
throw Error('log4js configuration not specified');
const logger = log4js_1.default.getLogger(category);
logger.addContext('env', this._appEnv);
logger.addContext('name', this._appName);
logger.addContext('host', this._appHost);
logger.addContext('port', this._appPort);
return logger;
}
/**
* 缓存键值对数据
* @param key
* @param value
*/
setContext(key, value) {
this._context[key] = value;
}
/**
* 读取键值对数据
* @param key
*/
getContext(key) {
return this._context[key];
}
/**
* 删除键值对数据
* @param key
*/
delContext(key) {
delete this._context[key];
}
/**
* 创建多级文件夹
* @param dirname 文件夹路径
*/
mkdirsSync(dirname) {
if (fs_1.default.existsSync(dirname)) {
return true;
}
else {
if (this.mkdirsSync(path_1.default.dirname(dirname))) {
try {
fs_1.default.mkdirSync(dirname);
return true;
}
catch (e) {
return false;
}
}
else {
return false;
}
}
}
/**
* 获取IPV4地址
* @param request http请求
* @param headerField 代理服务器的请求头字段名称
*/
getIPV4(request, headerField) {
let ip = (request.headers ? request.headers[headerField || 'x-forwarded-for'] : null) || request.ip;
if (!ip || '::1' === ip)
ip = '127.0.0.1';
if (Array.isArray(ip))
ip = ip.join(',');
ip = ip.replace(/[:f]/gm, '');
ip = ip.split(/\s*,\s*/)[0];
ip = ip.trim() || '127.0.0.1';
return ip;
}
/**
* 格式化日期
* @param date
* @param fmt
*/
formatDate(date, fmt) {
const o = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"H+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
"q+": Math.floor((date.getMonth() + 3) / 3),
"S": date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (let k in o) {
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
return fmt;
}
/**
* 计算md5
* @param data 要计算编码的字符串
*/
getMd5(data) {
return crypto_js_1.default.MD5(data).toString();
}
/**
* 读取ssl证书并返回
*/
readSSLKerCert() {
return {
key: fs_1.default.readFileSync(this._appSSLs.key, { encoding: this._encode }),
cert: fs_1.default.readFileSync(this._appSSLs.cert, { encoding: this._encode })
};
}
/**
* 判断一个对象是否为空
* @param obj
*/
isEmptyObject(obj) {
for (let key in obj) {
return false;
}
return true;
}
/**
* 模拟休眠
* @param time 毫秒
*/
sleep(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, time);
});
}
get dir() { return this._appDir; }
get env() { return this._appEnv; }
get name() { return this._appName; }
get host() { return this._appHost; }
get inip() { return this._appInIP; }
get port() { return this._appPort; }
get ssls() { return !!this._appSSLs; }
get links() { return this._appLinks; }
get nodes() { return this._appNodes; }
get encode() { return this._encode; }
/**
* 根据环境变量创建上下文实例
* @param processEnv
* @param encode
*/
static createByProcessEnv(processEnv, encode = 'utf8') {
return new EnvContext(processEnv.MYAPP_DIR, processEnv.MYAPP_ENV, processEnv.MYAPP_NAME, processEnv.MYAPP_HOST, processEnv.MYAPP_INIP, processEnv.MYAPP_PORT, typeof processEnv.MYAPP_SSLS === 'string' ? JSON.parse(processEnv.MYAPP_SSLS) : processEnv.MYAPP_SSLS, typeof processEnv.MYAPP_LINKS === 'string' ? JSON.parse(processEnv.MYAPP_LINKS) : processEnv.MYAPP_LINKS, typeof processEnv.MYAPP_NODES === 'string' ? JSON.parse(processEnv.MYAPP_NODES) : processEnv.MYAPP_NODES, encode);
}
}
exports.EnvContext = EnvContext;