1.0.0 • Published 3 years ago

infrastructure-network-web v1.0.0

Weekly downloads
-
License
ISC
Repository
bitbucket
Last release
3 years ago

network-web

网络请求-web

Usage

token 刷新监听

export declare const reigistRefreshTokenEvent: (
  callback: () => Promise<any>
) => void;

request 请求

export declare const baseRequest: (option: Option) => Promise<any>;

使用示例

import { baseRequest, reigistRefreshTokenEvent } from "network-web";

// 配置请求头
const baseOptions = (params: requestParamsProps, method = "GET") => {
  const { url, data } = params;
  let contentType = "application/json";
  contentType = params.contentType || contentType;
  const user: LocalLoginInfoIpo = getLoginInfo();
  //请求头加devKey
  const timeStamp = new Date().getTime().toString();
  const md5TimeStamp = md5(`${timeStamp}lajsf.com`);
  const option: OptionType = {
    url: url.indexOf("http") !== -1 ? url : env.httpBaseUrl + url,
    data: data,
    method: method,
    header: {
      "content-type": contentType,
      tenantId: "nutritiondiet",
      devType: "4",
      userId: user?.userAccount?.kid || "",
      token: (user?.authInfo && user?.authInfo?.token) || "",
      devKey: `${timeStamp}${md5TimeStamp}`,
      appId: "diet",
      cooperationId: "1"
    },
    xhrFields: { withCredentials: true }
  };
  return option;
};

// 注册http 刷新token 回调
reigistRefreshTokenEvent(() => {
  return new Promise(function (resolve, reject) {
    const user: LocalLoginInfoIpo = getLoginInfo();
    const refreshToken = user?.authInfo?.refreshToken;
    const token = user?.authInfo?.token;
    if (!user.userInfo?.userId || !token || !refreshToken) {
      const error = {
        msg: "必传字段为空"
      };
      reject(error);
      return;
    }
    const requestToken = async function () {
      const auth = await api.appAuth.refreshToken({
        refreshToken: refreshToken,
        token: user?.authInfo?.token
      });
      const authInfo = { ...user.authInfo, ...auth };
      user.authInfo = authInfo;
      setCache(LOGIN_INFO, { ...user });
      const token = auth.token;
      resolve(token);
    };
    requestToken();
  });
});

// 处理请求数据
const handleResponse = (res: any, option: OptionType) => {
  //mock请求处理
  if (env.env === "dev" && mockDatas) {
    let mockUrl = String(option.url);
    mockUrl = mockUrl.replace(env.httpBaseUrl, "");
    const mockData = mockDatas[mockUrl];
    if (mockData) {
      return {
        data: mockData
      };
    }
  }

  //接口请求处理
  const code = res.data.code;
  switch (Number(code)) {
    case 200:
      return res.data;
    case 103:
    case 104:
    case 105: {
      //执行退出登录操作
      break;
    }
    case 100:
    case 1000: {
      toast(res.data.msg);
      throw res;
    }
    default: {
      throw res;
    }
  }
};

const request = (option: OptionType) => {
  return baseRequest(option)
    .then((res) => {
      console.warn(
        "--------请求数据--------",
        option,
        "--------响应数据--------",
        res
      );
      return handleResponse(res, option);
    })
    .catch((e) => {
      throw e;
    });
};

export const httpGet = (url: string, data?: any): Promise<any> => {
  const option = baseOptions({ url, data });
  return request(option);
};

export const httpPost = (url: string, data?: any): Promise<any> => {
  const option = baseOptions({ url, data }, "POST");
  return request(option);
};

export const httpDelete = (url: string, data?: any): Promise<any> => {
  const option = baseOptions({ url, data }, "DELETE");
  return request(option);
};

export const httpPut = (url: string, data?: any): Promise<any> => {
  const option = baseOptions({ url, data }, "PUT");
  return request(option);
};
1.0.0

3 years ago