mirror of
https://github.com/jiangrui1994/CloudSaver.git
synced 2026-01-13 16:48:46 +08:00
Initial commit for open-source version
This commit is contained in:
28
backend/src/utils/axiosInstance.ts
Normal file
28
backend/src/utils/axiosInstance.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import axios, { AxiosInstance, AxiosRequestHeaders } from "axios";
|
||||
import tunnel from "tunnel";
|
||||
import { config } from "../config";
|
||||
|
||||
export function createAxiosInstance(
|
||||
baseURL: string,
|
||||
headers: AxiosRequestHeaders,
|
||||
useProxy: boolean = false
|
||||
): AxiosInstance {
|
||||
let agent;
|
||||
|
||||
if (useProxy) {
|
||||
agent = tunnel.httpsOverHttp({
|
||||
proxy: {
|
||||
host: config.httpProxy.host,
|
||||
port: Number(config.httpProxy.port),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return axios.create({
|
||||
baseURL,
|
||||
timeout: 30000,
|
||||
headers,
|
||||
httpsAgent: useProxy ? agent : undefined,
|
||||
withCredentials: true,
|
||||
});
|
||||
}
|
||||
11
backend/src/utils/handleError.ts
Normal file
11
backend/src/utils/handleError.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Response, NextFunction } from "express";
|
||||
import { Logger } from "../utils/logger";
|
||||
export default function handleError(
|
||||
res: Response,
|
||||
error: any,
|
||||
message: string,
|
||||
next: NextFunction
|
||||
) {
|
||||
Logger.error(message, error);
|
||||
next(error || { success: false, message });
|
||||
}
|
||||
38
backend/src/utils/logger.ts
Normal file
38
backend/src/utils/logger.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
type LogLevel = "info" | "success" | "warn" | "error";
|
||||
|
||||
export const Logger = {
|
||||
info(...args: any[]) {
|
||||
this.log("info", ...args);
|
||||
},
|
||||
|
||||
success(...args: any[]) {
|
||||
this.log("success", ...args);
|
||||
},
|
||||
|
||||
warn(...args: any[]) {
|
||||
this.log("warn", ...args);
|
||||
},
|
||||
|
||||
error(...args: any[]) {
|
||||
this.log("error", ...args);
|
||||
},
|
||||
|
||||
log(level: LogLevel, ...args: any[]) {
|
||||
const timestamp = new Date().toISOString();
|
||||
const prefix = `[${timestamp}] [${level.toUpperCase()}]`;
|
||||
|
||||
switch (level) {
|
||||
case "success":
|
||||
console.log(prefix, ...args);
|
||||
break;
|
||||
case "warn":
|
||||
console.warn(prefix, ...args);
|
||||
break;
|
||||
case "error":
|
||||
console.error(prefix, ...args);
|
||||
break;
|
||||
default:
|
||||
console.log(prefix, ...args);
|
||||
}
|
||||
},
|
||||
};
|
||||
5
backend/src/utils/responseHandler.ts
Normal file
5
backend/src/utils/responseHandler.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Response } from "express";
|
||||
|
||||
export const handleResponse = (res: Response, data: any, success: boolean) => {
|
||||
res.json({ success, data });
|
||||
};
|
||||
Reference in New Issue
Block a user