Title

小程序函数封装

/**- wechat request encapsulation-**/

/**
 * @param.data   表示请求参数
 * @param.method 表示请求方法  默认 "get"
 * @param.loading  Boolean值  是否显示加载icon
 * @param.url 请求接口
 * @param.header  请求头
 * @param.success 请求成功,status为200时,可通过then((r)=>{})方式获取请求数据
 * 
*/
export function fetch(params) {
  let data = params.data || '',
    method = params.method || "get",
    url = params.url,
    loading = params.loading;
  return new Promise((resolve, reject) => {
    loading ? wx.showLoading({
      mask: false
    }) : null;
    wx.request({
      data,
      method,
      url,
      header: params.header || {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      success: (res) => {
        wx.hideLoading();
        console.log(`request:`,res.data)
        if (res.statusCode == 200) resolve(res.data);
        else wx.showToast({
          title: `${res.data.message}`,
          icon: `none`
        });
      },
      fail: (err) => {
        setTimeout(() => {
          wx.hideLoading();
        }, 1000);
        reject(`requestErr:`, err);
      },
      complete: () => {}
    })
  })
};

/**
 * urlsErr - check request url 
 * @param.c 表示请求返回结果状态 c值时status值,可验证登录
 * */ 
export function urlsErr(c) {
  let e = c,
    n = new Map([
      [502, "Bad Gateway!"],
      [404, "Not Found!"],
      [400, "not exist!"]
    ]);
  return new Promise(() => {
    wx.showToast({
      title: n.get(e),
      icon: `none`
    })
  })
};

/**
 * @see loginCheck 返回的是Boolean值
 * @param.t 指 this;
 * @param.url 指 即将要进入目标页面的路径
 * */ 
export function loginCheck(t, url, dec) {
  let c = !wx.getStorageSync('rd_session') ? false : true;
  return new Promise((resolve) => {
    if(!c){
      t.setData({
        authorization:{
          show: true,
          message: {
            url,
            dec
          }
        }
      });
    };
    resolve(c)
  })
};
/**
 * @see upChooseImage  仅仅支持图片一张一张上传  so:upChooseImage - > upLoadImage
 * @param.n  表示 相册 还是 拍照; 
 * @param.c  表示按钮字体颜色 默认黑色; 
 * @param.m  表示 可一次性上传多少张!
 * */ 
export function upChooseImage(params) {
  let n = params.a || ['相册', '拍照'],
    c = params.c || `#000000`,
    m = params.m || 3; 
  return new Promise((resolve, reject) => {
    wx.showActionSheet({
      itemList: n,
      itemColor: c,
      success: (r) => {
        if (!r.cancel)
          if (r.tapIndex == 0)
            wx.chooseImage({
              count: m,
              sourceType: ['album'],
              success: (r) => {
                resolve(r);
              }
            })
        else if (r.tapIndex == 1)
          wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['camera'],
            success: (r) => {
              resolve(r);
            }
          })

      },
      fail: (e) => {
        reject(`chooseImage:`, e);
      }
    })
  })
};
/**
 * @see upLoadImage 仅仅支持图片一张一张上传  so:upChooseImage - > upLoadImage
 * @param.arr 表示 相册数组
 * @param.url  表示 服务器路径
 * */ 
export function upLoadImage(arr, url) {
  let token = loginCheck(),
    TOKENNAME = `Authori-zation`,
    header = {
      "Content-Type": `multipart/form-data`,
      [TOKENNAME]: `Bearer ${token}`,
    },
    u = url;
  return new Promise((resolve, reject) => {
    for (let i = 0; arr.length > i; ++i) {
      wx.showLoading({
        title: `正在上传:${i}/${arr.length}`
      });
      wx.uploadFile({
        filePath: arr[i],
        name: 'file',
        url: u,
        header,
        formData: {
          'images': arr[i]
        },
        success: r => {
          let exist = JSON.parse(r.data).status;
          getErr(exist);
          if (exist != 410000 && exist != 410001) {
            if (i + 1 == arr.length) {
              wx.hideLoading();
              setTimeout(() => {
                resolve(r);
                wx.showToast({
                  title: `上传成功`,
                  icon: `none`
                });
              }, 500);
              return;
            }
          } else {
            wx.showToast({
              title: `内容和图册不能为空!`,
              icon: 'none'
            })
          }
        },
        fail: e => {
          wx.hideLoading();
          reject(`uploadFile:`, e);
        }
      })
    }
  });
};
/**
 * @see timerFormat 时间格式化
 * @param.t  表示时间
 * @param.b  表示显示格式 Boolean值  常规格式: years/month/day/hour:minute  大致时间格式 :几天前,几月前等...
 * */ 
export function timeFormat(t, b) {
  function e(t) {
    return t < 10 ? "0" + t.toString() : t.toString();
  };

  function l(u) {
    u = u.toString();
    return u[1] ? u : `0${u}`
  };
  let n = new Date(t),
    y = n.getFullYear(),
    m = n.getMonth() + 1,
    d = n.getDate(),
    w = n.getDay(),
    h = n.getHours(),
    i = n.getMinutes(),
    s = n.getSeconds(),
    f = e(n.getMinutes()),
    u = (n.getSeconds(), new Date()),
    r = 0;
  if (b) {
    return r = Date.now() - t, r <= 60 ? "刚刚" : 60 < r && r <= 3600 ? Math.round(r / 60) + "分钟前" : 3600 < r && r <= 3600 * 24 ? Math.round(r / 3600) + "小时前" : 3600 * 24 < r && r <= 1296000 ? Math.round(r / (3600 * 24)) + "天前" : r > 1296000 && r == u.getFullYear() ? m + "-" + d + " " + e(h) + ":" + f : y + "-" + m + "-" + d + " " + e(h) + ":" + f;
  } else {
    return `${[y, m, d].map(l).join('/')} ${[h, i, s].map(l).join(':')}`;
  }
};
/**
 * @param.t 表示时间,返回值是 例:星期一;
 * */ 
export function getWeek(t) {
  let e = null;
  if ("string" != typeof t && "number" != typeof t) return t;
  let w = (t = new Date(t)).getDay();
  return 0 == w && (e == "星期日"),
    1 == w && (e == "星期一"),
    2 == w && (e == "星期二"),
    3 == w && (e == "星期三"),
    4 == w && (e == "星期四"),
    5 == w && (e == "星期五"),
    6 == w && (e == "星期六");
};
/**
 * @param.t 表示时间,返回值时 例: 一月;
 * */   
export function getMouth(t) {
  return t ? ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"][new Date(t).getMonth()] + "月" : t;
};
// err - code - collection -check login
export function getErr(c) {
  let e = c,
    n = new Map([
      [410000, "未登录"],
      [410001, "登录已过期,重新登录"]
    ]);
  return wx.showToast({
    title: n.get(e),
    icon: "none",
    success: () => {
      setTimeout(() => {
        /*-- 是否授权登录 --*/ 
      }, 1000)
    }
  })
};
/**
 * @param.n 表示天数 从0开始数  例:n 为0时 ,表示未来一天的时间;
 * @param.l 表示语言 英语和中文之间切换
 * 
*/
export function futureDay(n, l) {
  let t = new Date(),
    e = new Date().getFullYear(),
    d = new Date(t.setDate(t.getDate() + n)).getDate(),
    m = t.getMonth() + 1,
    w = t.getDay(),
    i = t.getDay(),
    y = `${e}${m < 10 ? `0`+ m : m}${d < 10 ? `0`+ d : d}`;
  let ls = l || 1;
  switch (w) {
    case 0:
      w = `${ls == 1 ? `日` :`SUN`}`;
      break;
    case 1:
      w = `${ls == 1 ? `一` :`MON`}`;
      break;
    case 2:
      w = `${ls == 1 ? `二` :`TUE`}`;
      break;
    case 3:
      w = `${ls == 1 ? `三` :`WEB`}`;
      break;
    case 4:
      w = `${ls == 1 ? `四` :`THU`}`;
      break;
    case 5:
      w = `${ls == 1 ? `五` :`FRI`}`;
      break;
    case 6:
      w = `${ls == 1 ? `六` :`SAT`}`;
      break;
  };
  return {
    d,
    m,
    w,
    i,
    y
  }
};
// next week
function futureWeek(o, l) {
  let a = [];
  for (let i = 0; i <= o; ++i) {
    a.push(futureDay(i, l))
  };
  return new Promise((resolve, reject) => {
    resolve(a);
  });
};

/** 
 * @see  秒转化为分秒
 * @param.endTime 指单位为秒的时间
 * @param.f 指格式,Boolean值, 默认格式 00:00:00
 * */  
export function formateSeconds(endTime, f){
  let secondTime = parseInt(endTime)//将传入的秒的值转化为Number
  let min = 0// 初始化分
  let h =0// 初始化小时
  let result=''
  if(secondTime>60){//如果秒数大于60,将秒数转换成整数
    min=parseInt(secondTime/60)//获取分钟,除以60取整数,得到整数分钟
    secondTime=parseInt(secondTime%60)//获取秒数,秒数取佘,得到整数秒数
    if(min>60){//如果分钟大于60,将分钟转换成小时
      h=parseInt(min/60)//获取小时,获取分钟除以60,得到整数小时
      min=parseInt(min%60) //获取小时后取佘的分,获取分钟除以60取佘的分
    }
  };
  let m = min < 10 ? `0${min}` : min, s = secondTime < 10 ? `0${secondTime}` : secondTime;
  
  result = f ? `${h.toString().padStart(2,'0')}:${min.toString().padStart(2,'0')}:${secondTime.toString().padStart(2,'0')}` : `${h == 0 ? `` : h + `h`}${m == 0 ? `` : m + `′`}${s == 0 ? `` : s + `″`}`
  return result 
}

/**
 * @see 分秒倒计时
 * @param.totalTime 指需要倒计的时间
 * @param.t 指当前页面的this
 * */ 
export function timeCountDown(totalTime){
  if(totalTime < 60 * 60){
    if (totalTime >= 0) {
      let minutes = Math.floor(totalTime / 60), seconds = Math.floor(totalTime % 60), time = minutes + "′" + seconds + "″";
      --totalTime;
      return time;
    } else {
      clearInterval(timer);
      let timer = setInterval("timeCountDown()", 1000);
    };
  }
};
/**
 * @param.t  表示 this
 * @param.p  表示 动画集合名
 * @param.h  表示 translateY的参数
 * @param.o  表示 opacity的参数
 * */  
export function animations(t, p, h, o) {
  let duration = 500,
    timingFunction = 'ease';
  let j = '{"' + p + '":""}';
  let he = h  +  `rpx`;
  let animation = wx.createAnimation({
    duration,
    timingFunction
  });
  return new Promise((resolve) => {
    let i = 1, next = true; 
    let a = setInterval(() => {
      if(next){
        animation.height(he).opacity(o).step();
        j = JSON.parse(j);
        j[p] = animation.export();
        t.setData({ j});
        next = true;
        return false;
      }else{
        animation.translateY(0).opacity(0).step();
        j = JSON.parse(j);
        j[p] = animation.export();
        t.setData({ j});
        return false;
      };
    }, 300);
    setTimeout( () => { clearInterval(a);},300);
  })
};
// judgeNetwork
export function judgeNetwork(c) {
  wx.getNetworkType({
    success: (r) => {
      let n = r.networkType;
      if ("none" == n) {
        wx.showLoading({
          title: `暂无网络`,
          mask: false
        });
        setTimeout(() => {
          wx.hideLoading()
        }, 1000);
        judgeNetwork(c);
      } else {
        c(n);
      }
    },
    fail: (e) => {
      console.log(`err:`, e)
    }
  })
};
/**
 * @see storageTerm  --> 时效缓存
 * @param.s 表示类型 例:setStorageSync
 * @param.k 表示key值
 * @param.v 表示value值
 * @param.m 表示有效期是多久
 * */ 
export function storageTerm(s, k, v, m) {
  let t = m ? m : 3600;
  let e = parseInt(t);
  let i = Date.parse(new Date()) / 1000 + e;
  switch (s) {
    case s == "setStorageSync":
      wx.setStorageSync(k, v);
      break;
    case s == "setStorage":
      wx.setStorage({
        key: k,
        data: v
      });
      break;
    default:
      wx.setStorageSync(k, v);
      break;
  };
  if (e > 0) {
    s == "setStorageSync" ? wx.setStorageSync(k + "dt", i + "") : wx.setStorage({
      key: k + "dt",
      data: i + ""
    })
  } else {
    switch (s) {
      case s == "setStorageSync":
        wx.removeStorageSync(k + "dt", i + "");
        break;
      case s == "setStorage":
        wx.removeStorage({
          key: k + "dt",
          data: i + ""
        });
        break;
      default:
        break;
    };
  };
};
/**
 * @see getStorageTerm --> 读取时效缓存
 * @param.k 缓存读取 必须在有效期内
 * */ 
export function getStorageTerm(k) {
  if (!!wx.getStorageSync(k + 'dt')) {
    var dt = wx.getStorageSync(k + 'dt');
  } else {
    var dt = false
  }
  if (dt) {
    if (parseInt(dt) < Date.parse(new Date()) / 1000) {
      wx.removeStorageSync(k + 'dt');
      wx.removeStorage({
        key: k + 'dt'
      });
    } else {
      let r = wx.getStorageSync(k);
      if (r) {
        return r;
      } else {
        return false;
      };
    }
  } else {
    return false;
  };
};
// clearStorage
export function clearStorage() {
  wx.clearStorage();
  wx.clearStorageSync()
};
/*--音频版本兼容--*/
export function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

compareVersion('1.11.0', '1.9.9') // 1 
// 抛出 module
export default {
  fetch,
  upLoadImage,
  timeFormat,
  getWeek,
  getMouth,
  getErr,
  futureDay,
  futureWeek,
  animations,
  judgeNetwork,
  storageTerm,
  getStorageTerm,
  clearStorage,
  loginCheck,
  urlsErr,
  upChooseImage,
  compareVersion,
  formateSeconds,timeCountDown
}

 

posted @ 2021-06-17 14:30  谈亦行  阅读(300)  评论(0编辑  收藏  举报