Refactoring the backend

This commit is contained in:
jiangrui
2025-03-10 18:33:47 +08:00
parent 755a424530
commit a78ea7e5bd
36 changed files with 974 additions and 474 deletions

View File

@@ -4,7 +4,8 @@ import GlobalSetting from "../models/GlobalSetting";
import { GlobalSettingAttributes } from "../models/GlobalSetting";
import * as cheerio from "cheerio";
import { config } from "../config";
import { Logger } from "../utils/logger";
import { logger } from "../utils/logger";
import { injectable } from "inversify";
interface sourceItem {
messageId?: string;
@@ -20,20 +21,20 @@ interface sourceItem {
cloudType?: string;
}
@injectable()
export class Searcher {
private axiosInstance: AxiosInstance | null = null;
private static instance: Searcher;
private api: AxiosInstance;
constructor() {
this.initializeAxiosInstance();
this.initAxiosInstance();
Searcher.instance = this;
}
private async initializeAxiosInstance(isUpdate = false): Promise<void> {
let settings = null;
if (isUpdate) {
settings = await GlobalSetting.findOne();
}
private async initAxiosInstance() {
const settings = await GlobalSetting.findOne();
const globalSetting = settings?.dataValues || ({} as GlobalSettingAttributes);
this.axiosInstance = createAxiosInstance(
this.api = createAxiosInstance(
config.telegram.baseUrl,
AxiosHeaders.from({
accept:
@@ -56,8 +57,11 @@ export class Searcher {
: undefined
);
}
public async updateAxiosInstance() {
await this.initializeAxiosInstance(true);
public static async updateAxiosInstance(): Promise<void> {
if (Searcher.instance) {
await Searcher.instance.initAxiosInstance();
}
}
private extractCloudLinks(text: string): { links: string[]; cloudType: string } {
@@ -111,7 +115,7 @@ export class Searcher {
}
});
} catch (error) {
Logger.error(`搜索频道 ${channel.name} 失败:`, error);
logger.error(`搜索频道 ${channel.name} 失败:`, error);
}
});
@@ -125,10 +129,10 @@ export class Searcher {
async searchInWeb(url: string) {
try {
if (!this.axiosInstance) {
if (!this.api) {
throw new Error("Axios instance is not initialized");
}
const response = await this.axiosInstance.get(url);
const response = await this.api.get(url);
const html = response.data;
const $ = cheerio.load(html);
const items: sourceItem[] = [];
@@ -205,7 +209,7 @@ export class Searcher {
});
return { items: items, channelLogo };
} catch (error) {
Logger.error(`搜索错误: ${url}`, error);
logger.error(`搜索错误: ${url}`, error);
return {
items: [],
channelLogo: "",