美文网首页
Taro项目之请求API.HttpClient.ts封装

Taro项目之请求API.HttpClient.ts封装

作者: 是素净呀丶 | 来源:发表于2020-02-26 15:59 被阅读0次

    经过上次对运行命令的改装,我们便可轻松的获取到不同环境以使用不用的请求地址。
    大致封装代码如下:

    import Taro from "@tarojs/taro";
    import { request, RequestParams } from "@tarojs/taro";
    import { get, eq, merge, includes, delay, curryRight } from "lodash";
    import { LOGIN_KEYS } from "../const/index";
    import { PopupService, GlobalService } from "../service/";
    
    export interface IResponseData<T = any> {
      code: string;
      msg: string;
      data: T;
    }
    
    class HttpRequest {
      static BASE_URL = {
        dev: "http://dev.***.com",
        test: "https://test.***.com",
        prd: "https://www.***.com"
      }[process.env.BUILD_ENV];
    
      static baseOptions = {
        header: {
          "content-type": "application/json",
          Authorization: `${Taro.getStorageSync(
            LOGIN_KEYS.USER_TOKEN_TYPE
          )} ${Taro.getStorageSync(LOGIN_KEYS.USER_TOKEN)}`
        },
        dataType: "json"
      };
    
      static generateFullUrl = (url: string) =>
        `${HttpRequest.BASE_URL}${url.startsWith("/") ? "" : "/"}${url}`;
    
      static requestSuccessHandler = (res, isCheckResponse, rs, rj) => {
        if (!isCheckResponse) {
          rs(res);
    
          return;
        }
    
        const statusCode = get(res, "statusCode");
        if (!eq(statusCode, 200)) {
          const error = get(res, "data.error");
    
          if (includes(["unauthorized", "invalid_token"], error)) {
            rj(res);
    
            PopupService.$showToast({
              title: "授权已失效,请重新授权登录",
              icon: "error",
              duration: 2000
            });
    
            delay(() => {
              try {
                GlobalService.$loginOut();
              } catch (er) {
                console.error(er);
              }
            }, 2000);
    
            return;
          }
    
          PopupService.$message({
            message: get(
              res,
              "data.error_description",
              get(res, "data.msg", JSON.stringify(get(res, "data")))
            ),
            type: "error"
          });
    
          rj(res);
          return;
        } else {
          rs(res.data);
        }
      };
    
      static requestFailHandler = (error, rj) => {
        PopupService.$message({
          message: JSON.stringify(get(error, "errMsg", "Unknow Error")),
          type: "error"
        });
        rj(error);
      };
    
      static request(url, method, data = {}, options = {}, isCheckResponse = true) {
        const $options = merge(
          {},
          HttpRequest.baseOptions,
          {
            header: {
              Authorization: `${Taro.getStorageSync(
                LOGIN_KEYS.USER_TOKEN_TYPE
              )} ${Taro.getStorageSync(LOGIN_KEYS.USER_TOKEN)}`
            }
          },
          options,
          { method }
        );
    
        const authorization = get($options, "header.Authorization");
        const token =
          typeof authorization === "string" ? authorization.split(" ")[1] : null;
        if (!token) {
          return new Promise((__, rj) =>
            rj(new Error("TOKEN IS REQUIRED"))
          ) as Promise<IResponseData>;
        }
    
        if (!GlobalService.isLogin() && !url.includes("/uaa/oauth/token")) {
          return new Promise((__, rj) =>
            rj(new Error("LOGIN IS INVALID"))
          ) as Promise<IResponseData>;
        }
    
        return new Promise((rs, rj) =>
          request(
            merge({}, $options, {
              url: HttpRequest.generateFullUrl(url),
              data,
              success: curryRight(HttpRequest.requestSuccessHandler, 4)(
                isCheckResponse,
                rs,
                rj
              ) as typeof HttpRequest.requestSuccessHandler,
              fail: curryRight(
                HttpRequest.requestFailHandler,
                2
              )(rj) as typeof HttpRequest.requestFailHandler
            }) as RequestParams
          )
        ) as Promise<IResponseData>;
      }
    
      static get = async (url, data = {}, options = {}, isCheckResponse = true) =>
        HttpRequest.request(url, "GET", data, options, isCheckResponse);
    
      static post = async (url, data = {}, options = {}, isCheckResponse = true) =>
        HttpRequest.request(url, "POST", data, options, isCheckResponse);
    
      static put = async (url, data = {}, options = {}, isCheckResponse = true) =>
        HttpRequest.request(url, "PUT", data, options, isCheckResponse);
    
      static delete = async (
        url,
        data = {},
        options = {},
        isCheckResponse = true
      ) => HttpRequest.request(url, "DELETE", data, options, isCheckResponse);
    }
    
    export { HttpRequest };
    export default HttpRequest;
    
    

    相关文章

      网友评论

          本文标题:Taro项目之请求API.HttpClient.ts封装

          本文链接:https://www.haomeiwen.com/subject/fblbchtx.html