55 lines
1.3 KiB
TypeScript
55 lines
1.3 KiB
TypeScript
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
|
|
export interface HttpRequestOptions {
|
|
url: string;
|
|
method?: HttpMethod;
|
|
data?: unknown;
|
|
header?: Record<string, string>;
|
|
}
|
|
|
|
export interface HttpResponse<T = any> {
|
|
statusCode: number;
|
|
data: T;
|
|
header: Record<string, string>;
|
|
}
|
|
|
|
export class HttpStatusError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public readonly statusCode: number,
|
|
public readonly data?: unknown
|
|
) {
|
|
super(message);
|
|
this.name = 'HttpStatusError';
|
|
}
|
|
}
|
|
|
|
export const httpRequest = <T = any>(options: HttpRequestOptions) => {
|
|
return new Promise<HttpResponse<T>>((resolve, reject) => {
|
|
uni.request({
|
|
url: options.url,
|
|
method: options.method || 'GET',
|
|
data: options.data,
|
|
header: options.header || {},
|
|
success: (response: any) => {
|
|
resolve({
|
|
statusCode: Number(response.statusCode),
|
|
data: response.data as T,
|
|
header: response.header || {}
|
|
});
|
|
},
|
|
fail: reject
|
|
});
|
|
});
|
|
};
|
|
|
|
export const toFormUrlEncoded = (data: Record<string, unknown> = {}) => {
|
|
return Object.entries(data)
|
|
.filter(([, value]) => value !== undefined && value !== null)
|
|
.map(([key, value]) => {
|
|
const normalizedValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
|
|
return `${encodeURIComponent(key)}=${encodeURIComponent(normalizedValue)}`;
|
|
})
|
|
.join('&');
|
|
};
|