Open Aaronphy opened 2 years ago
handler factory
import { ipcMain } from 'electron';
class HandlerFactory {
public static create(scope:string ,bind: any){
return (name:string, fn:(...args:any[])=>void, includeEvent = false) =>
ipcMain.handle(`${scope}.${name}`,(...args:any[])=>{
if(!includeEvent) args = args.slice(1);
return fn.bind(bind)(...args);
});
}
}
background 30s countdown
let st = Date.now(),
i = 0,
itv = setInterval(()=>{
i = ~~((Date.now() - st)/1000);
if(i >= 3){
clearInterval(itv)
alert('time over')
}
},1000);
get the ip in nodejs
import { networkInterfaces, NetworkInterfaceInfo } from 'os';
export const getPrivateIPNInfos = (): (NetworkInterfaceInfo | undefined)[] => Object.values(networkInterfaces()) .flatMap(infos => infos?.filter(i => i.family === 'IPv4')) .filter( info => info?.address.match(/(^127.)|(^10.)|(^172.1[6-9].)|(^172.2[0-9].)|(^172.3[0-1].)|(^192.168.)/) !== null );
export const getPrivateIPs = (): (string | undefined)[] => getPrivateIPNInfos().map(i => i?.address);
export const getPrivateExternalIPNInfos = (): (NetworkInterfaceInfo | undefined)[] => Object.values(networkInterfaces()) .flatMap(infos => infos?.filter(i => !i.internal && i.family === 'IPv4')) .filter( info => info?.address.match(/(^10.)|(^172.1[6-9].)|(^172.2[0-9].)|(^172.3[0-1].)|(^192.168.)/) !== null );
export const getPrivateExternalIPs = (): (string | undefined)[] => getPrivateExternalIPNInfos().map(i => i?.address);
retry promise and sleep timer
// 工具函数,用于延迟一段时间
const sleep = (time: number) => {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
};
// 工具函数,用于包裹 try - catch 逻辑
const awaitErrorWrap = async <T, U = any>(
promise: Promise<T>
): Promise<[U | null, T | null]> => {
try {
const data = await promise;
return [null, data];
} catch (err: any) {
return [err, null];
}
};
// 重试函数
export const retryRequest = async <T>(
promise: () => Promise<T>,
retryTimes: number = 3,
retryInterval: number = 500
) => {
let output: [any, T | null] = [null, null];
for (let a = 0; a < retryTimes; a++) {
output = await awaitErrorWrap(promise());
if (output[1]) {
break;
}
console.log(`retry ${a + 1} times, error: ${output[0]}`);
await sleep(retryInterval);
}
return output;
};
usage
import { retryRequest } from "xxxx"; import axios from "axios";
const request = (url: string) => { return axios.get(url); };
const [err, data] = await retryRequest(request("https://request_url"), 3, 500);
> method decorator
```typescript
export const retryDecorator = (
retryTimes: number = 3,
retryInterval: number = 500
): MethodDecorator => {
return (_: any, __: string | symbol, descriptor: any) => {
const fn = descriptor.value;
descriptor.value = async function (...args: any[]) {
// 这里的 retryRequest 就是刚才的重试函数
return retryRequest(fn.apply(this, args), retryTimes, retryInterval);
};
};
};
usage
import { retryRequest } from "xxxx"; import axios from "axios";
class RequestClass { @retryDecorator(3, 500) static async getUrl(url: string) { return axios.get(url); } }
const [err, data] = await RequestClass.getUrl("https://request_url");
//版本比较
const isVersionNewerOrEqual = (oldVer, newVer) => {
try {
const oldParts = oldVer.split('.');
const newParts = newVer.split('.');
for (let i = 0; i < newParts.length; i++) {
const a = parseInt(newParts[i]);
const b = parseInt(oldParts[i]);
if (a > b) return true;
if (a < b) return false;
}
return true;
} catch (e) {
return false;
}
};