分类 TS工具类 下的文章


import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

export default class ApiClient {
  private axiosInstance: AxiosInstance;

  constructor(config?: AxiosRequestConfig) {
    this.axiosInstance = axios.create(config);
  }

  public async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.axiosInstance.get(url, config);
    return response.data;
  }

  public async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.axiosInstance.post(url, data, config);
    return response.data;
  }

  public async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.axiosInstance.put(url, data, config);
    return response.data;
  }

  public async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.axiosInstance.delete(url, config);
    return response.data;
  }
}

使用

import ApiClient from "../utils/apiClient";
 const api = new ApiClient({ baseURL: 'https://api.example.com' });
 export default async function getUser() {
     return await api.get('/users');
}

import nodemailer from "nodemailer";

interface MailOptions {
  to: string;
  subject: string;
  text?: string;
  html?: string;
}

export class EmailUtil {
  private static readonly transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_PASSWORD,
    },
  });

  public static async sendEmail(options: MailOptions): Promise<void> {
    const mailOptions: nodemailer.SendMailOptions = {
      from: process.env.EMAIL_USER,
      to: options.to,
      subject: options.subject,
    };

    if (options.text) {
      mailOptions.text = options.text;
    }

    if (options.html) {
      mailOptions.html = options.html;
    }

    try {
      await this.transporter.sendMail(mailOptions);
      console.log(`Email sent to ${options.to}: ${options.subject}`);
    } catch (error) {
      console.error(`Error sending email to ${options.to}: ${error}`);
    }
  }
}

使用方法


//使用方法
 await EmailUtil.sendEmail({
     to: "recipient@example.com",
     subject: "Test Email",
     text: "This is a test email.",
});

import { CronJob } from 'cron';

class CronUtil {
  // jobMap记录了所有的CronJob实例
  private static jobMap: Map<string, CronJob> = new Map<string, CronJob>();

  /**
   * 添加一个定时任务
   * @param name 任务名称,用于唯一标识任务
   * @param cronTime cron表达式
   * @param onTick 定时任务回调函数
   * @param onComplete 任务完成回调函数
   */
  static addJob(name: string, cronTime: string, onTick: () => void, onComplete?: () => void): void {
    if (this.jobMap.has(name)) {
      throw new Error(`Cron job with name ${name} already exists`);
    }

    const job = new CronJob(cronTime, onTick, onComplete, true);
    this.jobMap.set(name, job);
  }

  /**
   * 启动指定名称的任务
   * @param name 任务名称
   */
  static startJob(name: string): void {
    const job = this.jobMap.get(name);
    if (!job) {
      throw new Error(`No cron job found with name ${name}`);
    }

    if (!job.running) {
      job.start();
    }
  }

  /**
   * 停止指定名称的任务
   * @param name 任务名称
   */
  static stopJob(name: string): void {
    const job = this.jobMap.get(name);
    if (!job) {
      throw new Error(`No cron job found with name ${name}`);
    }

    if (job.running) {
      job.stop();
    }
  }

  /**
   * 停止所有任务
   */
  static stopAllJobs(): void {
    for (const [_, job] of this.jobMap) {
      job.stop();
    }
  }
}

export default CronUtil;

使用方式

//任务调度器
CronUtil.addJob('myJob', '*/5 * * * * *', () => {
   console.log('Job executed!');
});

CronUtil.startJob('myJob');