TongHui的博客 - TS工具类
type: channel
link: https://tonghui.domcer.com/index.php/category/TS%E5%B7%A5%E5%85%B7%E7%B1%BB/
description: TS工具类
items: 基于 axios 封装 请求类
items: 基于 uuid 生成UUID
items: 基于 nodemailer 发送电子邮件
items: 基于 cron 的定时任务调度器

基于 axios 封装 请求类
type: item
date: 2023-05-05T15:17:54+08:00
description: 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'); }

基于 uuid 生成UUID
type: item
date: 2023-05-05T15:15:59+08:00
description: import { v4 as uuidv4 } from 'uuid'; class UUIDGenerator { static generate(): string { return uuidv4(); } } export default UUIDGenerator; 使用方法UUIDGenerator.generate()

基于 nodemailer 发送电子邮件
type: item
date: 2023-05-05T14:59:00+08:00
description: 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.", });

基于 cron 的定时任务调度器
type: item
date: 2023-05-05T14:57:00+08:00
description: 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');