refactor: 封装请求
This commit is contained in:
@@ -5,33 +5,11 @@ import axios, {
|
||||
type AxiosResponse,
|
||||
} from "axios";
|
||||
|
||||
/** 后端 `{ code, msg, data }`;约定 `code === 0` 表示成功 */
|
||||
export type ApiEnvelope<T = unknown> = {
|
||||
code: number;
|
||||
msg: string;
|
||||
data: T;
|
||||
};
|
||||
|
||||
/** HTTP 状态非 2xx(或 Axios 报错)但其 body 仍是业务信封且 `code !== 0` 时抛出 */
|
||||
export class LotteryApiBizError extends Error {
|
||||
readonly code: number;
|
||||
readonly data: unknown;
|
||||
|
||||
constructor(message: string, code: number, data: unknown) {
|
||||
super(message);
|
||||
this.name = "LotteryApiBizError";
|
||||
this.code = code;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
/** body 不是约定的信封结构 */
|
||||
export class LotteryApiEnvelopeError extends Error {
|
||||
constructor(message = "响应不是约定的 { code, msg, data }") {
|
||||
super(message);
|
||||
this.name = "LotteryApiEnvelopeError";
|
||||
}
|
||||
}
|
||||
import {
|
||||
LotteryApiBizError,
|
||||
LotteryApiEnvelopeError,
|
||||
} from "@/types/api/errors";
|
||||
import { isApiEnvelope } from "@/types/api/envelope";
|
||||
|
||||
export function setLotteryRequestLocale(locale: string | null): void {
|
||||
if (locale === null) {
|
||||
@@ -69,18 +47,6 @@ function acceptLanguage(loc: ReturnType<typeof requestLocale>): string {
|
||||
return "en-US,en;q=0.9";
|
||||
}
|
||||
|
||||
function isEnvelope(v: unknown): v is ApiEnvelope {
|
||||
if (v === null || typeof v !== "object") {
|
||||
return false;
|
||||
}
|
||||
const o = v as Record<string, unknown>;
|
||||
return (
|
||||
typeof o.code === "number" &&
|
||||
typeof o.msg === "string" &&
|
||||
"data" in o
|
||||
);
|
||||
}
|
||||
|
||||
const baseURL = process.env.NEXT_PUBLIC_LOTTERY_API_BASE_URL?.trim();
|
||||
|
||||
/**
|
||||
@@ -112,7 +78,7 @@ function mergeLocaleHeaders(
|
||||
* `code !== 0` 抛 {@link LotteryApiBizError}。
|
||||
*/
|
||||
export function unwrapData<T>(payload: unknown): T {
|
||||
if (!isEnvelope(payload)) {
|
||||
if (!isApiEnvelope(payload)) {
|
||||
throw new LotteryApiEnvelopeError();
|
||||
}
|
||||
if (payload.code !== 0) {
|
||||
@@ -138,7 +104,7 @@ export async function request<T>(config: AxiosRequestConfig): Promise<T> {
|
||||
} catch (err: unknown) {
|
||||
if (isAxiosError(err) && err.response?.data !== undefined) {
|
||||
const body = err.response.data;
|
||||
if (isEnvelope(body) && body.code !== 0) {
|
||||
if (isApiEnvelope(body) && body.code !== 0) {
|
||||
throw new LotteryApiBizError(body.msg, body.code, body.data);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user