This commit is contained in:
2024-09-18 16:35:40 +08:00
commit 2903d63ee6
77 changed files with 14842 additions and 0 deletions

138
src/utils/request.ts Normal file
View File

@@ -0,0 +1,138 @@
import { redirect } from 'next/navigation'; // 如果在 SSR 中需要使用
import queryString from 'query-string';
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
interface Params {
cacheTime?: number; //缓存时间单位为s。默认强缓存0为不缓存
params?: Record<string, any>;
}
interface Props extends Params {
url: string;
method: Method;
}
type Config = { next: { revalidate: number } } | { cache: 'no-store' } | { cache: 'force-cache' };
class Request {
/**
* 请求拦截器
*/
interceptorsRequest({ url, method, params, cacheTime }: Props) {
let queryParams = ''; //url参数
let requestPayload = ''; //请求体数据
//请求头
const headers = {
authorization: `Bearer ...`,
};
const config: Config =
cacheTime || cacheTime === 0
? cacheTime > 0
? { next: { revalidate: cacheTime } }
: { cache: 'no-store' }
: { cache: 'force-cache' };
if (method === 'GET' || method === 'DELETE') {
//fetch对GET请求等不支持将参数传在body上只能拼接url
if (params) {
queryParams = queryString.stringify(params);
url = `${url}?${queryParams}`;
}
} else {
//非form-data传输JSON数据格式
if (!['[object FormData]', '[object URLSearchParams]'].includes(Object.prototype.toString.call(params))) {
Object.assign(headers, { 'Content-Type': 'application/json' });
requestPayload = JSON.stringify(params);
}
}
return {
url,
options: {
method,
headers,
body: method !== 'GET' && method !== 'DELETE' ? requestPayload : undefined,
...config,
},
};
}
/**
* 响应拦截器
*/
interceptorsResponse<T>(res: Response): Promise<T> {
return new Promise((resolve, reject) => {
const requestUrl = res.url;
if (res.ok) {
res
.clone()
.text()
.then((text) => {
try {
const data = JSON.parse(text);
console.log("resp code", data.code)
if (data.code == 200) {
return resolve(res.json() as Promise<T>);
} else {
return reject({ code: data.code, message: data.message, url: requestUrl });
}
} catch (err) {
return reject({ message: text, url: requestUrl });
}
});
} else {
res
.clone()
.text()
.then((text) => {
try {
const errorData = JSON.parse(text);
return reject({ code: res.status, message: errorData || '接口错误', url: requestUrl });
} catch {
return reject({ code: res.status, message: text, url: requestUrl });
}
});
}
});
}
async httpFactory<T>({ url = '', params = {}, method }: Props): Promise<T> {
const req = this.interceptorsRequest({
url: process.env.NEXT_PUBLIC_BASEURL + url,
method,
params: params.params,
cacheTime: params.cacheTime,
});
const res = await fetch(req.url, req.options);
return this.interceptorsResponse<T>(res);
}
async request<T>(method: Method, url: string, params?: Params): Promise<T> {
return this.httpFactory<T>({ url, params, method });
}
get<T>(url: string, params?: Params): Promise<T> {
return this.request('GET', url, params);
}
post<T>(url: string, params?: Params): Promise<T> {
return this.request('POST', url, params);
}
put<T>(url: string, params?: Params): Promise<T> {
return this.request('PUT', url, params);
}
delete<T>(url: string, params?: Params): Promise<T> {
return this.request('DELETE', url, params);
}
patch<T>(url: string, params?: Params): Promise<T> {
return this.request('PATCH', url, params);
}
}
const request = new Request();
export default request;

10
src/utils/utils.ts Normal file
View File

@@ -0,0 +1,10 @@
/**
* 校验手机号码的函数
* @param phoneNumber - 要校验的手机号码
* @returns 如果手机号码有效则返回 true否则返回 false
*/
export function isValidPhoneNumber(phoneNumber: string): boolean {
// 正则表达式,用于匹配有效的手机号码(中国大陆的手机号码格式)
const phoneNumberRegex = /^1[3-9]\d{9}$/;
return phoneNumberRegex.test(phoneNumber);
}