提交 a7e8f4ee authored 作者: supj's avatar supj

1、克隆外部库,将多个仓库合并为一个仓库

上级
.idea/
node_modules/
dist/
docs/
/package-lock.json
/yarn.lock
/jest.config.js
// import typescript from "rollup-plugin-typescript2";
// import resolve from 'rollup-plugin-node-resolve';
// import commonjs from 'rollup-plugin-commonjs';
import typescript from "rollup-plugin-typescript";
import {terser} from 'rollup-plugin-terser';
import dts from "rollup-plugin-dts";
import path from "path";
const pkg = require('../package.json')
const resolveFile = (...args) => path.resolve(...args);
let inputFile=resolveFile("./src/index.ts")
let libName = "generalTools"
export default [
{
// 生成 .d.ts 类型声明文件
input: inputFile,
output: {
file: resolveFile(pkg.types),
format: 'es',
},
plugins: [dts()],
},
{
input: inputFile,
output: [
{
file: resolveFile(pkg.main),
format: "cjs",
exports:"default"
},
{
file:resolveFile(pkg.module),
format: "es",
},
{
file:resolveFile(pkg.browser),
format: "umd",
name: libName,
},
],
plugins: [
typescript({
exclude: "node_modules/**",
typescript: require("typescript"),
}),
terser()
],
}
];
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
{
"name": "mf-lib",
"version": "1.0.0",
"description": "",
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.mjs",
"browser": "./lib/umd/index.umd.js",
"types": "./lib/index.d.ts",
"type": "commonjs",
"scripts": {
"lib": " rimraf ./lib && rollup -c ./build/rollup.config.js",
"build": "rimraf ./dist && tsc -p tsconfig.json",
"test": "jest --no-cache && exit 0",
"doc": "typedoc --options typedoc.json && npm run doc:gh-fix",
"doc:gh-fix": "touch docs/.nojekyll"
},
"author": "bluefox",
"license": "ISC",
"files": [
"lib"
],
"devDependencies": {
"@types/jest": "^27.0.3",
"dts": "^0.1.1",
"jest": "^27.4.3",
"rimraf": "^3.0.2",
"rollup": "^2.60.2",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-dts": "^4.0.1",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript": "^1.0.1",
"rollup-plugin-typescript2": "^0.31.1",
"ts-jest": "^27.1.0",
"tslib": "^2.3.1",
"typedoc": "^0.19.2",
"typedoc-neo-theme": "^1.0.10",
"typescript": "^4.0.5",
"yargs": "^17.3.0"
}
}
import {DateHelper} from "../helper/DateHelper";
import {MonthData} from "./MonthData"
import {DayData} from "./DayData"
export class CalendarData {
monthCount: number
startYear: number
startMonth: number
monthDataList: Array<MonthData>
/**
* @param monthCount 月份个数
* @param startYear 起始年
* @param startMonth 起始月
*/
constructor(monthCount: number, startYear?: number, startMonth?: number) {
this.monthCount = monthCount;
this.startYear = startYear && startYear >= 1970 ? startYear : new Date().getFullYear();
this.startMonth = startMonth && startMonth > 0 && startMonth <= 12 ? startMonth : new Date().getMonth() + 1;
const months = new Array<MonthData>();
let monthData = CalendarData.getCalendarMonth(this.startYear, this.startMonth);
months.push(monthData)
for (let i = 1; i < monthCount; i++) {
monthData = CalendarData.getNextMonth(monthData.year, monthData.month);
months.push(monthData)
}
this.monthDataList = months;
}
/**
* 获取当前时间 (2018-08-15)
*/
static getCurrentFormatDateString(): string {
const date = new Date();
return date.getFullYear() + "-" + DateHelper.formatNumber(date.getMonth() + 1) + "-" + DateHelper.formatNumber(date.getDate());
}
/**
* 获取日历数据
* @param year
* @param month
*/
static getCalendarMonth(year: number, month: number): MonthData {
const monthInfo = new MonthData(year, month);
const weekDay = DateHelper.getWeekDay(year, month);
if (weekDay > 0) {
//月份的第一天不是表的第一天。需要在前面插入上个月数据
const lastMonthInfo = DateHelper.getLastMonthInfo(year, month);
const lastMonthDays = DateHelper.getMonthDays(lastMonthInfo.year, lastMonthInfo.month)
for (let j = 0; j < weekDay; j++) {
const currentDay = lastMonthDays - weekDay + 1 + j;
const dayInfo = new DayData(lastMonthInfo.year, lastMonthInfo.month, currentDay);
dayInfo.isSupplementDay = true;
monthInfo.dayItems.unshift(dayInfo)
}
}
const size = monthInfo.dayItems.length;
//为了列表显示(个数必须是7的倍数),必须补充空数据
const emptyDays = 7 - size % 7;
if (emptyDays < 7) {
const nextMonthInfo = DateHelper.getNextMonthInfo(year, month)
for (let j = 0; j < emptyDays; j++) {
let dayInfo = new DayData(nextMonthInfo.year, nextMonthInfo.month, (j + 1));
dayInfo.isSupplementDay = true;
monthInfo.dayItems.push(dayInfo)
}
}
return monthInfo;
}
/**
* 获取上个月的数据
* @param year
* @param month
*/
static getLastMonthData(year: number, month: number): MonthData {
const info = DateHelper.getLastMonthInfo(year, month);
return CalendarData.getCalendarMonth(info.year, info.month)
}
/**
* 获取下个月的数据
* @param year
* @param month
*/
static getNextMonth(year: number, month: number): MonthData {
const info = DateHelper.getNextMonthInfo(year, month);
return CalendarData.getCalendarMonth(info.year, info.month)
}
/**
* 获取当前月份的日历数据
*/
static getCurrentMonth(): MonthData {
const date = new Date();
return CalendarData.getCalendarMonth(date.getFullYear(), date.getMonth() + 1)
}
/**
* 获取日历基础数据(从当前月,往后推)
* @param count
* @returns {Array}
*/
static getCalendarMonthList(count: number): Array<MonthData> {
const months = [];
let data = CalendarData.getCurrentMonth();
months.push(data)
for (let i = 1; i < count; i++) {
data = CalendarData.getNextMonth(data.year, data.month);
months.push(data)
}
return months;
}
}
import {DateHelper} from '../helper/DateHelper'
export class DayData {
year: number;
month: number;
day: number;
isSupplementDay: boolean;
titleName: string;
formatDay: string;
time: number;
constructor(year: number, month: number, day: number) {
this.year = year;
this.month = month;
this.day = day;
this.isSupplementDay = false;
this.titleName = String(day);
this.formatDay = `${year}-${DateHelper.formatNumber(month)}-${DateHelper.formatNumber(day)}`;
const date = new Date(this.formatDay);
date.setHours(0, 0, 0, 0)
this.time = date.getTime();
}
equals(object: DayData) {
return this.year === object.year && this.month === object.month && this.day === object.day
}
toString() {
return "year= " + this.year + " year= " + this.year + " year= " + this.year;
}
}
import {DayData} from "./DayData";
import {DateHelper} from "../helper/DateHelper";
export class MonthData {
titleName: string;
year: number;
month: number;
dayItems: Array<DayData>;
constructor(year: number, month: number) {
this.titleName = String(month);
this.year = year;
this.month = month;
const days = DateHelper.getMonthDays(year, month);
this.dayItems = [];
for (let i = 1; i <= days; i++) {
const dayInfo = new DayData(this.year, this.month, i);
this.dayItems.push(dayInfo);
}
}
toString(): string {
return "year= " + this.year + " month= " + this.month;
}
}
export class ArrayHelper {
static makeUpGroupList(list: Array<any>, groupNumber: number): Array<any> {
if (list && list.length > 0) {
const newList = [...list]
if (groupNumber < 2) {
return newList;
}
let endCount = newList.length % groupNumber;
if (endCount > 0) {//补全数据
for (let i = 0, len = groupNumber - endCount; i < len; i++) {
newList.push({})
}
}
return newList;
}
return list;
}
/**
* 将数据分组
* @param value 数据源
* @param groupNumber 分组的个数
* @returns {[]|*} 返回分组后的列表
*/
static grouping(value: Array<any> | string, groupNumber: number): Array<Array<any>> {
if (value && groupNumber > 0) {
const groupList = [];
let endLength = value.length;
let startIndex = 0;
let endIndex = groupNumber;
while (startIndex < endLength) {
groupList.push(value.slice(startIndex, endIndex))
startIndex = startIndex + groupNumber
endIndex = endIndex + groupNumber
}
return groupList;
}
return [];
}
}
import {dateConstants} from './DateConstants'
class CountDownInfo {
time: number;
day: number;
hour: number;
minute: number;
second: number;
constructor(time: number) {
let hourTime = time % dateConstants.dayMillis;//剩余的小时部分时间
let minuteTime = time % dateConstants.hourMillis;//剩余的分钟部分时间
let secondTime = time % dateConstants.minuteMillis;//剩余的秒部分时间
this.time = time;
this.day = Math.floor(time / dateConstants.dayMillis);
this.hour = Math.floor(hourTime / dateConstants.hourMillis);
this.minute = Math.floor(minuteTime / dateConstants.minuteMillis);
this.second = Math.floor(secondTime / dateConstants.secondMillis);
}
format(value: number): string {
return value >= 10 ? value + '' : "0" + value;
}
}
type CountDownFinishCallback = () => void;
type CountDownCallback = (info: CountDownInfo) => void;
export class CountDownTimer {
private millisInFuture: number;
private readonly mInterval: number;
private onCountDownFinishListener: CountDownFinishCallback;
private onCountDownListener: CountDownCallback;
private timeOutId: NodeJS.Timeout;
/**
* @param millisInFuture 时间毫秒数
* @param countDownInterval 时间毫秒数(单位间隔)
*/
constructor(millisInFuture: number, countDownInterval: number) {
this.millisInFuture = millisInFuture;
this.mInterval = countDownInterval;
this.onCountDownFinishListener = undefined;
this.onCountDownListener = undefined;
this.timeOutId = undefined;
}
addCountDownListener(listener: CountDownCallback): void {
if (listener && typeof listener === 'function') {
this.onCountDownListener = listener;
}
}
addFinishListener(listener: CountDownFinishCallback): void {
if (listener && typeof listener === 'function') {
this.onCountDownFinishListener = listener;
}
}
start(): void {
if (!this.timeOutId && this.onCountDownListener != undefined) {
this.timeOutId = setInterval(() => {
this.millisInFuture = this.millisInFuture - this.mInterval;
if (this.millisInFuture > 0) {
this.onCountDownListener(CountDownTimer.getTimeInfo(this.millisInFuture));
} else {
this.cancel();
if (this.onCountDownFinishListener !== undefined) {
this.onCountDownFinishListener();
}
}
}, this.mInterval);
}
}
cancel(): void {
if (this.timeOutId) {
clearTimeout(this.timeOutId);
this.timeOutId = undefined;
}
}
static getTimeInfo(time: number): CountDownInfo {
return new CountDownInfo(time);
}
}
const dayMillis = 86400000;//一天的毫秒数
const hourMillis = 3600000;//小时的毫秒数
const minuteMillis = 60000;//分的毫秒数
const secondMillis = 1000;//秒的毫秒数
export const dateConstants = {
dayMillis:dayMillis,
hourMillis:hourMillis,
minuteMillis:minuteMillis,
secondMillis:secondMillis,
};
export type DateType = string | number | Date
export type MonthDayNumber = 29 | 28 | 31 | 30
export type Callback=(...args:any)=>void;
import {dateConstants, DateType, MonthDayNumber} from "./DateConstants"
///yyyy-MM-dd HH:mm:ss
const formatDateList = [
{
symbolList: ["yyyy", "YYYY"],
getValue: function (date: Date): string {
return DateHelper.formatNumber(date.getFullYear());
}
},
{
symbolList: ["MM"],
getValue: function (date: Date): string {
return DateHelper.formatNumber(date.getMonth() + 1);
}
},
{
symbolList: ["DD", "dd"],
getValue: function (date: Date): string {
return DateHelper.formatNumber(date.getDate());
}
},
{
symbolList: ["HH", "hh"],
getValue: function (date: Date): string {
return DateHelper.formatNumber(date.getHours());
}
},
{
symbolList: ["mm"],
getValue: function (date: Date): string {
return DateHelper.formatNumber(date.getMinutes());
}
},
{
symbolList: ["SS", "ss"],
getValue: function (date: Date): string {
return DateHelper.formatNumber(date.getSeconds());
}
},
]
export class DateHelper {
/**
* 获取日期实例
* 兼容ios new Date('2020-10-10') 返回Invalid Date
* @param date
*/
static getDateInstance(date: DateType): Date {
if (date instanceof Date) {
return date;
}
if (typeof date === 'string' && date.indexOf('-') > 0) {//兼容ios new Date('2020-10-10') 返回Invalid Date
const reg = new RegExp("-", "g");
date = date.replace(reg, '/')
}
return new Date(date);
}
/**
* 获取某年某月第一天是星期几
* @param year
* @param month
*/
static getWeekDay(year: number, month: number): number {
const date = new Date(year, month - 1, 1);
return date.getDay();
}
/**
* 格式化数字符串
* @param num
*/
static formatNumber(num: number): string {
return num > 9 ? num + '' : "0" + num;
}
static isToday(date: DateType): boolean {
let currentDate = new Date();
let orderDate = DateHelper.getDateInstance(date);
return currentDate.getFullYear() === orderDate.getFullYear() && orderDate.getMonth() === currentDate.getMonth() && orderDate.getDate() === currentDate.getDate();
}
//格式化日期 YYYY-MM-DD
static getFormatDate(date: DateType): string {
const dateInstance = DateHelper.getDateInstance(date);
return dateInstance.getFullYear() + "-" + DateHelper.formatNumber(dateInstance.getMonth() + 1) + "-" + DateHelper.formatNumber(dateInstance.getDate());
}
//获取当前日期
static getCurrentFormatDate(): string {
return DateHelper.getFormatDate(new Date())
}
/**
* 获取当前日期所在月份的天数
* @param date
*/
static getDaysInMonth(date: DateType): MonthDayNumber {
const dateInstance = DateHelper.getDateInstance(date);
const month = dateInstance.getMonth() + 1;
return DateHelper.getMonthDays(dateInstance.getFullYear(), month);
}
/**
* 获取星期名称
* @param date 日期
* @param isEnglish true 表示是英文
*/
static getWeekName(date: DateType, isEnglish: boolean = false): string {
const dateInstance = DateHelper.getDateInstance(date);
const weekDay = dateInstance.getDay()
if (weekDay === 0) {
return isEnglish ? 'Sunday' : '周日';
} else if (weekDay === 1) {
return isEnglish ? 'Monday' : "周一";
} else if (weekDay === 2) {
return isEnglish ? 'Tuesday' : '周二';
} else if (weekDay === 3) {
return isEnglish ? 'Wednesday' : '周三';
} else if (weekDay === 4) {
return isEnglish ? 'Thursday' : '周四';
} else if (weekDay === 5) {
return isEnglish ? 'Friday' : '周五';
} else if (weekDay === 6) {
return isEnglish ? 'Saturday' : '周六';
}
return '';
}
/**
* 是否是闰年
* @param year
*/
static isLeapYear(year: number): boolean {
return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
}
/**
* 获取指定月份天数
* @param year
* @param month
* @returns {number}
*/
static getMonthDays(year: number, month: number): MonthDayNumber {
if (month === 2) {
return DateHelper.isLeapYear(year) ? 29 : 28;
}
const bigMonths = [1, 3, 5, 7, 8, 10, 12]
if (bigMonths.includes(month)) {
return 31;
}
return 30;
}
/**
*获取下个月信息
* @param year
* @param month
*/
static getNextMonthInfo(year: number, month: number) {
const newMonth = month >= 12 ? 1 : month + 1;
const newYear = month >= 12 ? year + 1 : year;
return {year: newYear, month: newMonth}
}
/**
* 获取上个月信息
* @param year
* @param month
*/
static getLastMonthInfo(year: number, month: number) {
//获取上个月实际月份
const newMonth = month == 1 ? 12 : month - 1;
//获取实际年份
const newYear = month == 1 ? year - 1 : year;
return {year: newYear, month: newMonth}
}
static diffTime(startTime: number, endTime: number, unitTime: number): number {
const diffTimeNum = endTime - startTime
return Math.floor((diffTimeNum / unitTime) * 100) / 100
}
/**
*相差年份数
* @param startTime
* @param endTime
*/
static diffYears(startTime: number, endTime: number) {
let number = DateHelper.diffMonths(startTime, endTime);
return Math.floor(number / 12 * 100) / 100;
}
/**
* 相差月分数
* @param startTime
* @param endTime
*/
static diffMonths(startTime: number, endTime: number) {
let miniTime = Math.min(startTime, endTime);
let maxTime = Math.max(startTime, endTime);
const startDate = DateHelper.getDateInstance(miniTime);
const endDate = DateHelper.getDateInstance(maxTime);
let diffYear = endDate.getFullYear() - startDate.getFullYear();
let startMonth = startDate.getMonth() + 1;
let endMonth = endDate.getMonth() + 1;
if (endMonth < startMonth) {
diffYear = diffYear - 1;
endMonth = endMonth + 12;
}
return Number.parseInt((diffYear * 12 + endMonth - startMonth).toFixed(0))
}
/**
* 相差天数
* @param startTime
* @param endTime
*/
static diffDays(startTime: number, endTime: number) {
return DateHelper.diffTime(startTime, endTime, dateConstants.dayMillis)
}
/**
* 相差小时数
* @param startTime
* @param endTime
*/
static diffHours(startTime: number, endTime: number) {
return DateHelper.diffTime(startTime, endTime, dateConstants.hourMillis)
}
/**
* 相差分数
* @param startTime
* @param endTime
*/
static diffMinutes(startTime: number, endTime: number) {
return DateHelper.diffTime(startTime, endTime, dateConstants.minuteMillis)
}
/**
* 相差月秒数
* @param startTime
* @param endTime
*/
static diffSeconds(startTime: number, endTime: number) {
return DateHelper.diffTime(startTime, endTime, dateConstants.secondMillis)
}
/**
* 格式化时间
* @param date
* @param formatStyle
*/
static formatDateString(date: DateType, formatStyle: string): string {
let format = String(formatStyle);
if (formatStyle) {
let dateInstance = DateHelper.getDateInstance(date);
formatDateList.forEach(formatItem => {
for (let i = 0, len = formatItem.symbolList.length; i < len; i++) {
if (format.indexOf(formatItem.symbolList[i]) >= 0) {
format = format.replace(formatItem.symbolList[i], formatItem.getValue(dateInstance))
break;
}
}
})
}
return format;
}
}
const eventsHolder = {
observerList: [],//观察对象列表
stickyEvents: [],//粘性事件(消息)
}
function getRegisterType(eventType: string): string {
return eventType ? eventType : "defaultType"
}
/**
* 订阅回调
*/
type Subscriber = (params: any) => void;
export class EventBus {
/**
* 发送粘性事件消息(同一个类型,只保留最后一个)
* @param msg 消息
* @param eventType 事件类型
*/
static postSticky(msg: any, eventType: string): void {
const registerType = getRegisterType(eventType);
const findIndex = eventsHolder.stickyEvents.findIndex(item => item.eventType === registerType);
if (findIndex >= 0) {
eventsHolder.stickyEvents[findIndex].msg = msg;
} else {
eventsHolder.stickyEvents.push({
eventType: registerType,
msg: msg,
})
}
EventBus.post(msg, registerType);
}
/**
* 发送事件消息
* @param msg 消息
* @param eventType 事件类型
*/
static post(msg: any, eventType: string): void {
const postType = getRegisterType(eventType);
eventsHolder.observerList.forEach(item => {
if (postType === item.eventType && item.subscriber && typeof item.subscriber === "function") {
item.subscriber({eventType: item.eventType, msg: msg});
}
})
}
/**
* //注册一个事件(同一类型只能注册一次,即同一函数名称名称,只能注册一次)
* @param observer 需要观察的对象
* @param eventType 观察的对象事件类型,可确省,默认为 "defaultType"
* @param sticky 是否是粘性事件,可确省,默认为false
* @param subscriber 订阅回调
*/
static register(observer: any, sticky = false, eventType = 'defaultType', subscriber: Subscriber): void {
if (subscriber) {
const registerType = getRegisterType(eventType);
let findIndex = eventsHolder.observerList.findIndex(item => item.observer === observer && item.eventType === eventType);
if (findIndex < 0) {
if (sticky) {
let findEvent = eventsHolder.stickyEvents.find(item => item.eventType === registerType);
if (findEvent && subscriber && typeof subscriber === "function") {
subscriber(findEvent);
}
}
eventsHolder.observerList.push({
observer: observer,
subscriber: subscriber,
eventType: registerType,
})
}
}
}
/**
* 解除注册
* @param observer
*/
static unregister(observer: any): void {
eventsHolder.observerList = eventsHolder.observerList.filter(item => item.observer !== observer);
}
/**
* 销毁所有(谨慎调用)
*/
static destroy(): void {
eventsHolder.stickyEvents = []
eventsHolder.observerList = []
}
}
let area = {
11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古",
21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏",
33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南",
42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆",
51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃",
63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外"
};
let weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];//权重
let checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];//校验码
/**
* 将15转为18位身份证
* @param cardNo
*/
function changeToEighteen(cardNo: string): string {
if (cardNo && cardNo.length === 15) {
//插入年月
let cardNo17 = cardNo.substring(0, 6) + '19' + cardNo.substring(6);
//计算组后一位
let sum = 0;
for (let i = 0; i < 17; i++) {
sum += Number.parseInt(cardNo17[i]) * weights[i];
}
return cardNo17 + checkCodes[sum % 11];
}
}
/**
* 判断身份证是否合法
* @param cardNo
*/
export function isIdCard(cardNo: string): boolean {
let regExp = new RegExp("(^\\d{15}$)|(^\\d{17}(\\d|X|x)$)");
// if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(cardNo)) {
if (!regExp.test(cardNo)) {
console.log('身份证长度或格式错误')
return false
}
let checkCode = String(cardNo);
if (checkCode.length === 15) {
checkCode = changeToEighteen(checkCode);
}
if (!area[checkCode.substring(0,2)]) {
console.log('身份证地区非法')
return false;
}
let birthday = (checkCode.substring(6, 10) + "-" + Number(checkCode.substring(10, 12)) + "-" + Number(checkCode.substring(12, 14))).replace(/-/g, "/");
let birthDate = new Date(birthday)
if (birthday != (birthDate.getFullYear() + "/" + (birthDate.getMonth() + 1) + "/" + birthDate.getDate())) {
console.log('身份证上的出生日期非法')
return false;
}
const currentDate = new Date();
currentDate.setHours(23,59,59)
birthDate.setHours(23,59,59)
if(currentDate.getTime()-birthDate.getTime()<0){
console.log('身份证上的出生日期非法,出生日期大于当前日期')
return false;
}
let time = currentDate.getFullYear() - birthDate.getFullYear();
if (time <0 || time > 150) {
console.log('出生日期岁数不合理')
return false;
}
// 身份证号码校验
let sum = 0;
for (let i = 0; i < checkCode.length - 1; i++) {
sum += Number.parseInt(checkCode[i]) * weights[i];
}
const lastCode = checkCodes[sum % 11]; //计算出来的最后一位身份证号码
if (checkCode[checkCode.length - 1] != lastCode) {
console.log('你输入的身份证号非法')
return false
}
return true;
}
export class LogUtils {
private readonly enableDebug;
constructor(debug) {
this.enableDebug = debug
}
getTag(tag: string): string {
return tag + '===================='
}
debug(msg: any): void {
if (this.enableDebug) {
console.debug(msg)
}
}
debugWithTag(tag: string, msg: any): void {
if (this.enableDebug) {
console.debug(this.getTag(tag), msg)
}
}
info(msg: any): void {
if (this.enableDebug) {
console.info(msg)
}
}
infoWithTag(tag: string, msg: any): void {
if (this.enableDebug) {
console.info(this.getTag(tag), msg)
}
}
log(msg: any): void {
if (this.enableDebug) {
console.log(msg)
}
}
logWithTag(tag: string, msg: any): void {
if (this.enableDebug) {
console.log(this.getTag(tag), msg)
}
}
error(msg: any): void {
if (this.enableDebug) {
console.error(msg)
}
}
errorWithTag(tag: string, msg: any): void {
if (this.enableDebug) {
console.error(this.getTag(tag), msg)
}
}
warn(msg: any): void {
if (this.enableDebug) {
console.warn(msg)
}
}
warnWithTag(tag: string, msg: any): void {
if (this.enableDebug) {
console.warn(this.getTag(tag), msg)
}
}
}
type WatchFun = (newVal: any, oldVal: any) => void
export class ObjectHelper {
/**
* 克隆函数
* @param func
*/
static cloneFunction(func: Function): any {
// const bodyReg = /(?<={)(.|\n)+(?=})/m;
const bodyReg = new RegExp("(?<={)(.|\\n)+(?=})","m");
// const paramReg = /(?<=\().+(?=\)\s+{)/;
const paramReg = new RegExp("(?<=\\().+(?=\\)\\s+{)");
const funcString = func.toString();
const param = paramReg.exec(funcString);
const body = bodyReg.exec(funcString);
if (param) {
const paramArr = param[0].split(',');
return body && body[0] ? new Function(...paramArr, body[0]) : new Function(...paramArr)
} else {
return body && body[0] ? new Function(body[0]) : new Function();
}
}
/**
* 深度克隆对象
* @param obj
* @param cache
*/
static cloneDeep(obj: object | Array<any>, cache?: WeakMap<object, object>): any {
if (obj === null || obj === undefined) {
return obj
}
if (obj instanceof Function) {
return ObjectHelper.cloneFunction(obj)
}
if (typeof obj !== 'object') {
return obj
} else {
if (obj instanceof Date) {
return new Date(obj)
}
if (obj instanceof RegExp) {
return new RegExp(obj)
}
if (obj instanceof Symbol) {
return Symbol(obj.description);
}
if (obj instanceof Map) {
let newMap = new Map<any, any>();
obj.forEach((value, key) => {
newMap.set(key, ObjectHelper.cloneDeep(value))
})
return newMap;
}
if (obj instanceof Set) {
let newSet = new Set<any>();
obj.forEach(((value, value2) => {
newSet.add(ObjectHelper.cloneDeep(value))
}))
return newSet;
}
if (obj instanceof Array) {
let newArray = new Array<any>();
for (let i = 0, len = obj.length; i < len; i++) {
newArray.push(ObjectHelper.cloneDeep(obj[i]));
}
return newArray;
}
if (obj instanceof Object) {
let weakMap = cache ? cache : new WeakMap<object, object>()
if (weakMap.get(obj)) {
// 防止循环引用,程序进入死循环
return cache.get(obj)
}
let newObject = {};
for (let key in obj) {
newObject[key] = ObjectHelper.cloneDeep(obj[key], weakMap)
}
weakMap.set(obj, newObject); // 缓存拷贝的对象,用于处理循环引用的情况
return newObject;
}
}
}
/**
* 将某个对象追加到当前对象中(扩展对象,类似java中的继承)
* @param targetObject
* @param sourceObject
*/
static extendObject(targetObject: object, sourceObject: object): object {
if (!sourceObject || typeof (sourceObject) !== 'object') {//源对象为空或者不是对象时
return targetObject;
}
if (targetObject && typeof (sourceObject) === 'object') {
Object.keys(sourceObject).forEach(sourceKey => {
if (typeof (targetObject[sourceKey]) === 'undefined') {//当前目标没有定义
targetObject[sourceKey] = sourceObject[sourceKey];
} else if (typeof (targetObject[sourceKey]) === 'object') {//当前目标不为空而且是对象时
ObjectHelper.extendObject(targetObject[sourceKey], sourceObject[sourceKey])
}
})
}
return targetObject;
}
/**
* 判断列表是是否包含特定的对象
* @param list
* @param object
*/
static containObject(list: Array<any>, object: any) {
if (!list || list.length < 1) {
return false
}
for (let i = 0, len = list.length; i < len; i++) {
if (ObjectHelper.equalDeep(list[i], object)) {
return true;
}
}
return false;
}
/**
* 深入比较对象(判断对象是否相等)
* @param object_1
* @param object_2
*/
static equalDeep(object_1: any, object_2: any): boolean {
let type1 = typeof object_1
let type2 = typeof object_2
if (type1 !== type2) {
return false
}
if (type1 === 'string' || type1 === 'number' || type1 === 'undefined' || type1 === 'boolean') {
return object_1 === object_2
}
if (type1 === 'object') {
if (object_1 instanceof Array) {
if (object_1.length !== object_1.length) {
return false
}
if (!object_1.every(item => ObjectHelper.containObject(object_2, item))) {
return false
}
return object_2.every(item => ObjectHelper.containObject(object_1, item));
} else {
let keys_1 = Object.keys(object_1)
let keys_2 = Object.keys(object_2)
if (keys_1.length !== keys_2.length) {
return false
}
let filterKeys = keys_2.filter(key => keys_1.includes(key))
if (filterKeys.length !== keys_1.length) {
return false
}
for (let i = 0, len = keys_1.length; i < len; i++) {
let equal = ObjectHelper.equalDeep(object_1[keys_1[i]], object_2[keys_1[i]])
if (!equal) {
return false
}
}
return true
}
}
return false;
}
/**
*
* @param keysList 取值字段列表 ["a","b"]
* @param valuesObject 目标对象{a:"a",b:"11",c:"aaaa",d:"dd"}
* @return {} //如{a:"a",b:"11"}
*/
static getObjectByList(keysList: Array<string>, valuesObject: object): object {
let newObject = {}
if (keysList && keysList.length > 0 && valuesObject && typeof valuesObject === 'object') {
for (let i = 0, len = keysList.length; i < len; i++) {
let key = keysList[i];
if (key) {
newObject[key] = valuesObject[key]
}
}
}
return newObject
}
/**
* 根据当前对象的key,从目标对象中取值
* @param keysObject {a:""}
* @param targetObject 目标对象{a:"a",b:"11",c:"aaaa",d:"dd"}
* @return {} //如{a:"a"}
*/
static getObjectByObject(keysObject: object, targetObject: object): object {
if (keysObject && targetObject && typeof keysObject === 'object' && typeof targetObject === 'object') {
let keys = Object.keys(keysObject)
return ObjectHelper.getObjectByList(keys, targetObject);
}
return {};
}
/**
* 从对象中获取值 (支持 "a.b.c" 获取值)
* @param obj
* @param keyWords
*/
static getValueFromObject(obj: object, keyWords): any {
if (typeof obj === 'object' && keyWords && typeof keyWords === 'string') {
if (obj[keyWords]) {
return obj[keyWords];
}
let indexOf = keyWords.indexOf(".");
if (indexOf < 0) {
return obj[keyWords]
} else {
const keys = keyWords.split(".")
if (obj[keys[0]] && obj[keys[0]] instanceof Object) {
const nextKeyWorks = keys.slice(1).join('.')
return ObjectHelper.getValueFromObject(obj[keys[0]], nextKeyWorks);
}
}
}
return "";
}
/**
* 设置监听器
*/
static addWatcher(data: object, watch: Record<string, (...args: any[]) => any>) {
Object.keys(watch).forEach(v => {
ObjectHelper.observe(data, v, watch[v]);
})
}
/**
* 监听属性 并执行监听函数
*/
static observe(obj: object, key: string, watchFun: WatchFun): void {
if (obj && typeof obj === 'object') {
let val = obj[key]; //给该属性设默认值
if (val) {
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set: function (value) {
let oldVal = val;
val = value;
watchFun(value, oldVal);
},
get: function () {
return val;
}
})
} else {
let indexOf = key.indexOf(".");
if (indexOf > 0) {
const objKey = key.substring(0, indexOf)
let newKey = key.substring(indexOf + 1);
ObjectHelper.observe(obj[objKey], newKey, watchFun)
}
}
}
}
}
export class StringHelper {
/**
* 替换所有
* @param content 当前文本
* @param pattern 旧字符串或者正则表达式
* @param newStr 要替换的内容
* @returns {*} 返回新的字符串
*/
static replaceAll(content: string, pattern: string, newStr: string) {
const reg = new RegExp(pattern, "g"); //创建正则RegExp对象
return content.replace(reg, newStr)
}
static isEmpty(str: string): boolean {
return !str || str.trim().length < 1;
}
/**
* 是否是组织机构代码
* @param code
* @returns {*|boolean}
*/
static isOrganizationCode(code: string): boolean {
// return /[0-9A-HJ-NPQRTUWXY]{8}-[0-9A-HJ-NPQRTUWXY]/g.test(code)
return new RegExp("^[0-9A-HJ-NPQRTUWXY]{8}-[0-9A-HJ-NPQRTUWXY]$").test(code)
}
/**
* 18位的统一信用代码
* @param code
* @returns {*|boolean}
*/
static isUnifiedCreditCode(code: string): boolean {
// return /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/.test(code)
return new RegExp("^[0-9A-HJ-NPQRTUWXY]{2}\\d{6}[0-9A-HJ-NPQRTUWXY]{10}$").test(code)
}
/**
* 校验手机号(严格校验)
* //移动号段:134 135 136 137 138 139 147 148 150 151 152 157 158 159 165 172 178 182 183 184 187 188 195 198
* // 联通号段:130 131 132 145 146 155 156 166 167 171 175 176 185 186
* // 电信号段:133 149 153 173 174 177 180 181 189 191 199
* // 虚拟运营商:170
* 分组如下
* //130 131 132 133 134 135 136 137 138 139
* //145 146 147 148 149
* //150 151 152 153 155 156 157 158 159
* // 165 166 167
* //170 171 172 173 174 175 176 177 178
* //180 181 182 183 184 185 186 187 188 189
* // 191 195 198 199
* @param phone
* @returns {boolean}
*/
static isPhoneNumber(phone: number | string): boolean {
const phoneStr = String(phone);
//手机号正则
// if (/^1[38][0-9]{9}$/.test(phoneStr)) {//校验//130 131 132 133 134 135 136 137 138 139 180 181 182 183 184 185 186 187 188 189号段
if (new RegExp("^1[38][0-9]{9}$").test(phoneStr)) {//校验//130 131 132 133 134 135 136 137 138 139 180 181 182 183 184 185 186 187 188 189号段
return true;
}
// if (/^14[56789][0-9]{8}$/.test(phoneStr)) {//校验14开头的号段
if (new RegExp("^14[56789][0-9]{8}$").test(phoneStr)) {//校验14开头的号段
return true
}
// if (/^15[012356789][0-9]{8}$/.test(phoneStr)) {//校验 1//150 151 152 153 155 156 157 158 159 开头的号段
if (new RegExp("^15[012356789][0-9]{8}$").test(phoneStr)) {//校验 1//150 151 152 153 155 156 157 158 159 开头的号段
return true;
}
// if (/^16[567][0-9]{8}$/.test(phoneStr)) {//校验 // 165 166 167 开头的号段
if (new RegExp("^16[567][0-9]{8}$").test(phoneStr)) {//校验 // 165 166 167 开头的号段
return true;
}
// if (/^17[012345678][0-9]{8}$/.test(phoneStr)) {//校验 //170 171 172 173 174 175 176 177 178 开头的号段
if (new RegExp("^17[012345678][0-9]{8}$").test(phoneStr)) {//校验 //170 171 172 173 174 175 176 177 178 开头的号段
return true;
}
// if (/^19[1589][0-9]{8}$/.test(phoneStr)) {//校验// 191 195 198 199 开头的号段
if (new RegExp("^19[1589][0-9]{8}$").test(phoneStr)) {//校验// 191 195 198 199 开头的号段
return true;
}
return false;
}
/**
* 判断是否是邮件地址
* @param email
* @returns {boolean}
*/
static isEmail(email: string): boolean {
if (email) {
// const regex = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
const regex = new RegExp("^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\\.[a-z]{2,}$")
return regex.test(email)
}
return false
}
/**
* 获取文本(过滤副文本标签)
* @param richText
*/
static filterRichText(richText: string): string {
if (!richText) {
return ""
}
const regExp = new RegExp('<[^<>]+>', 'g');
return richText.replace(regExp, "");
}
/**
* 从富文本中,查找img 标签,收集图片地址(只支持.png .jpg .jpeg 结尾)
* @param text 富文本
* @returns {[]} 返回图片列表
*/
static getImageListFromRichText(text: string): Array<string> {
const list = new Array<string>();
// let regular = /<img[^>]*>/g
let regular = new RegExp("<img[^>]*>","g")
let keysWords = text.match(regular)
if (keysWords && keysWords.length > 0) {
let srcReg =new RegExp("http\\S*((.jpg)|(.jpeg)|(.png))",'g')
// let srcReg = /http\S*((.jpg)|(.jpeg)|(.png))/g
keysWords.forEach(words => {
let strings = words.match(srcReg);
if (strings && strings.length > 0 && !list.includes(strings[0])) {
list.push(strings[0])
}
})
}
return list;
}
/*RGB颜色转换为16进制*/
static colorRbgToHex(rgbColor: string): string {
let lowerCaseColor = rgbColor.toLowerCase();
// let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
let reg = new RegExp("^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6 })$");
// if (/^(rgb|RGB)/.test(lowerCaseColor)) {
if (new RegExp("^(rgb|RGB)").test(lowerCaseColor)) {
let regExp = new RegExp("(?:\\(|\\)|rgb|RGB)*","g");
// let aColor = lowerCaseColor.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
let aColor = lowerCaseColor.replace(regExp, "").split(",");
let strHex = "#";
for (let i = 0; i < aColor.length; i++) {
let hex = Number(aColor[i]).toString(16);
if (hex === "0") {
hex += hex;
}
strHex += hex;
}
if (strHex.length !== 7) {
strHex = lowerCaseColor;
}
return strHex;
} else if (reg.test(lowerCaseColor)) {
// let aNum = lowerCaseColor.replace(/#/, "").split("");
let aNum = lowerCaseColor.replace("#", "").split("");
if (aNum.length === 6) {
return lowerCaseColor;
} else if (aNum.length === 3) {
let numHex = "#";
for (let i = 0; i < aNum.length; i += 1) {
numHex += (aNum[i] + aNum[i]);
}
return numHex;
}
}
return lowerCaseColor;
}
/**
*16进制颜色转为RGB格式
* @param hexColor 16进制颜色
* @returns {string} RGB格式颜色
*/
static colorHexToRgb(hexColor: string): string {
let sColor = hexColor.toLowerCase();
// let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
let regExp = new RegExp("^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$");
if (sColor && regExp.test(sColor)) {
if (sColor.length === 4) {
let sColorNew = "#";
for (let i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
//处理六位的颜色值
let sColorChange = [];
for (let i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return "rgb(" + sColorChange.join(",") + ")";
}
return sColor;
};
/**
* 将整数部分逢三一断
* @param value
* @returns {string}
*/
static formatNumber(value: String | number): string {
if (!value) {
return '0'
}
let strings = String(value).split('.');
// const leftNum = String(strings[0]).replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
let regExp = new RegExp("(\\d)(?=(?:\\d{3})+$)");
const leftNum = String(strings[0]).replace(regExp, '$1,');
if (strings.length > 1) {
return `${leftNum}.${strings[1]}`
}
return leftNum;
}
/**
* 通用脱敏
*
* 中文名字:只展示姓名第一个字
* 手机号:前三后四不脱敏,中间脱敏
* 身份证号:前6后4不脱敏,年月日脱敏
* 银行卡:前6位和后4位不脱敏,中间脱敏
* 其他 前6位和后4位不脱敏
* @param codeStr
* @return {string}
*/
static desensitize(codeStr) {
// if (/[\u4e00-\u9fa5]/.test(codeStr)) {
if (new RegExp("[\u4e00-\u9fa5]").test(codeStr)) {
return codeStr[0] + "***"
}
const str = String(codeStr)
let length = str.length;
if (length === 11) {//脱敏手机
return `${str.slice(0, 3)}****${str.slice(7, 11)}`
}
let regExp = new RegExp("^(.{6})(?:\\d+)(.{4})$");
//身份证、银行卡
// return str.replace(/^(.{6})(?:\d+)(.{4})$/, "\$1********\$2");
return str.replace(regExp, "\$1********\$2");
}
/**
* 生成唯一的uuid;
*/
static generateUUID(): string {
let d = new Date().getTime();
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c: string) {
const r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
}
export class UrlHelper {
/**
* 从地址中截取参数
* @param url
* @returns {Map<any, any>}
*/
static getQueryMapFromUrl(url: string): Map<string, any> {
const map = new Map()
if (url && url.indexOf("?") > 0) {
let paramsStr = url.substring(url.indexOf("?") + 1)
let groupList = paramsStr.split("&");
if (groupList && groupList.length > 0) {
groupList.forEach(item => {
let strings = item.split("=");
if (strings && strings.length > 1) {
map.set(strings[0], strings[1])
}
})
}
}
return map;
}
/**
* 获取跳转目标路径
* @param baseUrl
* @param params
* @returns {*}
*/
static getQueryUrl(baseUrl: string, params: object): string {
let hasStartFlag = baseUrl.indexOf('?') !== -1
if (params !== undefined && params instanceof Object) {
let requestUtl = baseUrl
for (let key in params) {
if (params[key] !== undefined) {
if (requestUtl.endsWith("?")) {
requestUtl = `${requestUtl}${key}=${params[key]}`
} else {
requestUtl = `${requestUtl}${!hasStartFlag ? '?' : '&'}${key}=${params[key]}`
if (!hasStartFlag) {
hasStartFlag = true
}
}
}
}
return requestUtl
} else {
return baseUrl
}
}
}
import {InterceptorsConfig} from "./InterceptorsConfig";
import {ResponseInterceptor} from './ResponseInterceptor'
const Method = {
GET: 'get',
POST: 'post',
DELETE: 'delete',
HEAD: 'head',
CONNECT: 'CONNECT',
OPTIONS: 'options',
PUT: 'put',
PATCH: 'patch',
TRACE: 'TRACE',
LINK: 'LINK',
UNLINK: 'unlink',
}
export default class HttpClient {
private readonly baseUrl: string;
private readonly platform: object;
private readonly requestInterceptorsConfig: InterceptorsConfig;
private readonly taskMap: Map<string, any>;
private readonly isMiniApp: boolean;
constructor(platform: object, isMiniApp: boolean, baseUrl: string, requestInterceptorsConfig: InterceptorsConfig) {
this.platform = platform;
this.baseUrl = baseUrl;
this.requestInterceptorsConfig = requestInterceptorsConfig;
this.taskMap = new Map<string, any>();
this.isMiniApp = isMiniApp;
}
post<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.POST, params, headers, cancelToken)
}
get<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
const requestUrl = HttpClient.getTargetUrl(path, params);//get请求得手动拼接参数
return this.request(requestUrl, Method.GET, {}, headers, cancelToken)
}
put<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.PUT, params, headers, cancelToken)
}
delete<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.DELETE, params, headers, cancelToken)
}
head<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.HEAD, params, headers, cancelToken)
}
options<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.OPTIONS, params, headers, cancelToken)
}
connect<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.CONNECT, params, headers, cancelToken)
}
trace<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.TRACE, params, headers, cancelToken)
}
patch<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.PATCH, params, headers, cancelToken)
}
link<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.LINK, params, headers, cancelToken)
}
unlink<T>(path: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
return this.request(path, Method.UNLINK, params, headers, cancelToken)
}
private static getTargetUrl(baseUrl: string, params: object): string {
if (params && Object.keys(params).length > 0) {
let hasStartFlag = baseUrl.indexOf('?') !== -1;
let requestUtl = baseUrl
for (let key in params) {
if (params[key] !== undefined) {
if (requestUtl.endsWith("?")) {
requestUtl = `${requestUtl}${key}=${params[key]}`
} else {
requestUtl = `${requestUtl}${!hasStartFlag ? '?' : '&'}${key}=${params[key]}`
if (!hasStartFlag) {
hasStartFlag = true
}
}
}
}
return requestUtl
}
return baseUrl
}
private request<T>(url: string, method: string, params?: any, headers?: any, cancelToken?: string): Promise<T> {
if (this.requestInterceptorsConfig && typeof this.requestInterceptorsConfig.getCacheData === "function") {
let cacheData = this.requestInterceptorsConfig.getCacheData(this.baseUrl, url, params);
if (cacheData !== undefined) {
return Promise.resolve(cacheData)
}
}
const defaultHeaders = {
'Content-Type': 'application/json',
...headers
}
//通过请求拦截器,获取统一的自定义请求头
const headerConfig = this.requestInterceptorsConfig && this.requestInterceptorsConfig.onRequestInterceptor ? this.requestInterceptorsConfig.onRequestInterceptor(defaultHeaders) : defaultHeaders;
const requestUrl = this.getRequestUrl(url);
const defaultOptions = {
baseURL: '',
url: requestUrl,
method: method,
data: params,
header: {
...headerConfig
}
}
// @ts-ignore
if (this.isMiniApp && this.platform && this.platform.request && typeof this.platform.request === 'function') {
return this.miniAppRequest(defaultOptions, cancelToken, url, params);
} else if (this.platform && typeof this.platform === 'function') {
return this.commonRequest(defaultOptions, cancelToken, url, params)
}
}
private getRequestUrl(url: string): string {
if (url.startsWith('https://') || url.startsWith('http://')) {
return url;
}
if (this.baseUrl) {
let endsWith = this.baseUrl.endsWith("/");
let startsWith = url.startsWith('/');
if (endsWith && startsWith) {
return this.baseUrl.substring(0, this.baseUrl.length - 1) + url;
} else if (!endsWith && !startsWith) {
return this.baseUrl + '/' + url;
}
return this.baseUrl + url
}
return url;
}
private miniAppRequest<T>(options: object, cancelToken: string | undefined, url: string, params?: any): Promise<T> {
return new Promise((resolve, reject) => {
const requestOptions = {
...options,
fail: (res: any) => {
if (cancelToken) {
this.taskMap.delete(cancelToken);
}
reject(res);
},
success: (res: any) => {
if (cancelToken) {
this.taskMap.delete(cancelToken);
}
this.successHandler(resolve, reject, res, url, params);
}
}
// @ts-ignore
let requestTask = this.platform.request(requestOptions);
if (cancelToken && requestTask) {
this.taskMap.set(cancelToken, requestTask)
}
})
}
private successHandler<T>(resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void, res: any, url: string, params: any) {
let responseData = this.getResponseData(res, url, params);
if (responseData.success) {
resolve(responseData.data);
} else {
reject(responseData.data);
}
}
private getResponseData(res: any, url: string, params?: any): ResponseInterceptor {
let responseData = {success: true, data: res};
if (this.requestInterceptorsConfig && typeof this.requestInterceptorsConfig.onResponseInterceptor === 'function') {
responseData = this.requestInterceptorsConfig.onResponseInterceptor(res);
}
if (responseData.success && this.requestInterceptorsConfig && typeof this.requestInterceptorsConfig.updateResponseCache === 'function') {
this.requestInterceptorsConfig.updateResponseCache(res, this.baseUrl, url, params);//缓存数据
}
return responseData;
}
private commonRequest<T>(options: object, cancelToken: string | undefined, url: string, params?: any): Promise<T> {
return new Promise((resolve, reject) => {
// @ts-ignore
this.platform(options)
.then((res: any) => {
this.successHandler(resolve, reject, res, url, params);
})
.catch((reason: any) => {
reject(reason);
})
})
}
}
import {InterceptorsConfig} from "./InterceptorsConfig";
import HttpClient from "./HttpClient";
const clientMap = new Map<string, HttpClient>();
type ClientInterceptors=()=>InterceptorsConfig;
export class HttpRequest {
/**
* 获取求实例
* @param platform 平台
* @param isMiniApp 是不是小程序
* @param baseUrl 地址
* @param interceptors 拦截器信息
*/
static getHttpClient(platform: any,isMiniApp:boolean,baseUrl: string,interceptors?:ClientInterceptors): HttpClient {
if (clientMap.has(baseUrl)) {
const httpClient = clientMap.get(baseUrl);
if (httpClient !== undefined) {
return httpClient;
}
}
let config = interceptors();
let httpClient = new HttpClient(platform, isMiniApp, baseUrl,config?config:{});
clientMap.set(baseUrl, httpClient)
return httpClient;
}
}
import {ResponseInterceptor} from './ResponseInterceptor'
/**
* 拦截器配置信息
*/
export interface InterceptorsConfig {
/**
* 接口请求拦截器
* @param header
*/
onRequestInterceptor?: (header: object) => object;
/**
* 接口响应拦截器
* @param response
*/
onResponseInterceptor?: (response: any) => ResponseInterceptor;
/**
* 获取缓存数据
* @param baseUrl
* @param url
* @param params
*/
getCacheData?:(baseUrl: string, url: string, params?: any)=> any;
/**
* 更新响应数据缓存
* @param data
* @param baseUrl
* @param url
* @param params
*/
updateResponseCache?:(data: any,baseUrl: string, url: string,params?: any)=> void;
/**
* 获取缓存的Key
* @param baseUrl
* @param url
* @param data
* @param params
*/
getCacheKey?:(baseUrl: string, url: string, data: any, params?: any)=> string;
}
export interface ResponseInterceptor {
success:boolean,
data:any,
}
import {dateConstants} from './helper/DateConstants'
import {CountDownTimer} from './helper/CountDownTimer'
import {CalendarData} from './calendar/CalendarData'
import {EventBus} from './helper/EventBus'
import {LogUtils} from './helper/LogUtils'
import {isIdCard} from "./helper/IdCardHelper";
import {StringHelper} from "./helper/StringHelper";
import {ArrayHelper} from "./helper/ArrayHelper"
import {ObjectHelper} from "./helper/ObjectHelper"
import {UrlHelper} from "./helper/UrlHelper"
import {DateHelper} from "./helper/DateHelper"
export type {CountDownTimer} from './helper/CountDownTimer'
export type {CalendarData} from './calendar/CalendarData'
export type {DayData} from './calendar/DayData'
export type {MonthData} from './calendar/MonthData'
export type {LogUtils} from './helper/LogUtils'
export type {isIdCard} from "./helper/IdCardHelper";
export type {StringHelper} from "./helper/StringHelper";
export type {ArrayHelper} from "./helper/ArrayHelper"
export type {ObjectHelper} from "./helper/ObjectHelper"
export type {UrlHelper} from "./helper/UrlHelper"
export type {DateHelper} from "./helper/DateHelper"
import {HttpRequest} from "./https/HttpRequest";
import HttpClient from "./https/HttpClient";
export type {InterceptorsConfig} from './https/InterceptorsConfig'
export type {ResponseInterceptor} from './https/ResponseInterceptor'
export default {
DateConstants: dateConstants,
CountDownTimer,
CalendarData,
LogUtils,
isIdCard,
StringHelper,
ObjectHelper,
DateHelper,
ArrayHelper,
UrlHelper,
HttpRequest,
HttpClient,
}
{
"compilerOptions": {
"outDir": "dist",
"target": "es5",
"module": "es2015",
"lib": [
"es2015",
"es2016",
"es2017",
],
"sourceMap": false,
"declaration": true,
"removeComments":false,
"declarationDir": "dist/types",
"typeRoots": [
"node_modules/@types"
],
"moduleResolution": "node",
"esModuleInterop": true
},
"typeAcquisition": {
},
"include": [
"src/"
],
"exclude": [
"/test",
"/lib",
"node_modules/"
]
}
{
"inputFiles": ["./src"],
"mode": "modules",
"out": "docs",
"exclude": "src/index.ts",
"theme": "./node_modules/typedoc-neo-theme/bin/default"
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论