@mamba-le/auth
Version:
150 lines • 4.1 kB
text/typescript
import debug from 'debug';
import localforage from 'localforage';
import lodash from 'lodash';
import { create } from 'mobx-persist';
export class AuthOptions {
/** 持久化序列化 */
static jsonify = true;
/**
* 日志输出
* @param namespace
* @param args
*/
static log(namespace: string, ...args) {
if (!AuthOptions.browser && process.env.NODE_ENV === 'production') {
args = lodash.filter(args, (x) => !lodash.isObject(x));
}
const log = debug(`【 Auth 】- ${namespace} -`);
log.enabled = true;
const [formatter, ...ars] = args;
log(formatter, ...ars);
log.destroy();
}
/**
* 日志输出带堆栈记录
* @static
* @param {string} namespace
* @param {*} args
* @memberof AuthOptions
*/
static trace(namespace: string, ...args) {
AuthOptions.log(namespace, ...args);
if (AuthOptions.browser) {
console?.groupCollapsed(
`%c -- [堆栈记录] --`,
`color:#f5222d`,
);
console?.trace(); // hidden in collapsed group
console?.groupEnd();
}
}
/**
* 微信 小程序 浏览器
* @readonly
* @memberof XTGlobal
*/
static get isWeappBowser() {
if (AuthOptions.browser) {
return lodash.some(['MiniProgramEnv', 'miniProgram'], (agent) =>
lodash.includes(
lodash.toLower(window.navigator.userAgent),
lodash.toLower(agent),
),
);
}
}
/**
* 是否浏览器环境
* @readonly
* @memberof AppConfig
*/
static get browser() {
return typeof window !== 'undefined';
}
/**
* 微前端环境
* @readonly
* @static
* @memberof AuthOptions
*/
static get micro() {
if (AuthOptions.browser) {
return window.__MICRO_APP_ENVIRONMENT__ || false
}
}
private static LocalforageKey = 'mamba-portal-auth';
private static _LocalForage: LocalForage = undefined;
/**
* localforage 访问器
* @readonly
* @private
* @static
* @memberof AuthOptions
*/
static get LocalForage() {
if (AuthOptions._LocalForage) {
return AuthOptions._LocalForage
}
const LocalForage = localforage.createInstance({
// driver: localforage.LOCALSTORAGE, // Forc
name: AuthOptions.LocalforageKey,
// storeName: AuthOptions.StorageKey,
})
AuthOptions._LocalForage = LocalForage
return LocalForage
};
/**
* 创建 storage
* @static
* @return {*}
* @memberof AuthOptions
*/
static createStorage() {
if (!AuthOptions.browser) {
return {
clear() {
AuthOptions.log('clear')
},
setItem(key, value) {
AuthOptions.log('setItem', key, value)
},
removeItem(key) {
AuthOptions.log('removeItem', key,)
},
getItem(key) {
AuthOptions.log('getItem', key,)
},
};
}
const { LocalForage } = AuthOptions;
return {
clear: LocalForage.clear,
setItem: LocalForage.setItem,
removeItem: LocalForage.removeItem,
getItem: LocalForage.getItem,
}
}
/**
* 持久化 mobx-persist
* @static
* @memberof basesOptions
*/
static createHydrate() {
const { createStorage, jsonify } = AuthOptions;
return create({
jsonify,
storage: createStorage(),
})
};
/**
* 写入校验
* @static
* @memberof AuthOptions
*/
static writeCheck() {
if (AuthOptions.micro) {
AuthOptions.log('微应用禁止写入')
throw '微应用禁止写入'
}
}
}