import { AxiosResponse } from 'axios'; import { IHttpResponse, IParam } from '../interface'; /** * 请求状态码 * */ export const HttpStatusMessage = { 200: '服务器成功返回请求的数据。', 201: '新建或修改数据成功。', 202: '一个请求已经进入后台排队(异步任务)。', 204: '删除数据成功。', 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。', 401: '用户没有权限(令牌、用户名、密码错误)。', 403: '用户得到授权,但是访问是被禁止的。', 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。', 406: '请求的格式不可得。', 410: '请求的资源被永久删除,且不会再得到的。', 422: '当创建一个对象时,发生一个验证错误。', 500: '服务器发生错误,请检查服务器。', 502: '网关错误。', 503: '服务不可用,服务器暂时过载或维护。', 504: '网关超时。', }; /** * 请求返回 * * @export * @class HttpResponse * @implements {IHttpResponse} */ export class HttpResponse implements IHttpResponse { readonly raw?: AxiosResponse; readonly success: boolean; readonly data?: T; readonly config?: IParam; readonly message?: string | undefined; readonly total?: number | undefined; /** * Creates an instance of HttpResponse. * * @param {*} [data] 数据 * @param {IResponse} [res] 结果 * @memberof HttpResponse */ constructor( data: T, res: AxiosResponse | null | undefined = null, statusCode = 200 ) { if (res) { this.raw = res; const { data: resData, status, statusText, headers } = res; this.success = status === 200; this.data = data ? data : resData; this.total = (res as any).total; this.message = resData && resData.message ? resData.message : statusText; if (headers && Object.keys(headers).length > 0) { const resConfig: IParam = {}; Object.keys(headers).forEach((key: string) => { Object.assign(resConfig, { [key]: headers[key] }); }); this.config = resConfig; } } else { this.data = data; this.message = (data as IParam).message ? (data as IParam).message : ''; this.success = statusCode === 200 ? true : false; } } }