微信小程序 API 封装 工具类

博客介绍了小程序项目结构,包含http.js、api.js、user.js、constants.js、config.js、util.js等文件,这些文件构成了项目的基础架构。

项目结构:
项目结构

http.js

import { config } from '../config/config'
import { message } from  '../common/message'
import { storageKeys } from '../common/constant'
import { promisify } from '../utils/util'

const request = async (url, data = {}, method) => {
  if (url.indexOf('http') < 0) {
    url = config.apiBaseUrl + url
  }

  let token = wx.getStorageSync(storageKeys.token)
  let promise = promisify(wx.request)({
    url,
    data,
    method,
    header: {
      'content-type': 'application/json',
      'token': token
    }
  }).then((res) => {
    if (res.statusCode >= 400) {
      if (!handleException(res)) {
        return false
      }
    }
    return res
  }).catch((res) => {
    if (!handleException(res)) {
      return false
    }
  })
  return promise
}

const Http = {
  get: function (url, data) {
    return request(url, data, 'GET')
  },
  post: function (url, data) {
    return request(url, data, 'POST')
  },
  put: function (url, data) {
    return request(url, data, 'PUT')
  }
}

// 统一异常处理的方案
const handleException = (error) => {
  let handled = false
  if (error.statusCode === 0 || error.statusCode === 200) {
    handled = true
  } else if (error.statusCode === 401) {
    handled = false
    // 移除token
    wx.removeStorageSync(storageKeys.token)
    // todo 跳转到登录页
  } else {
    handled = false
    wx.showToast({
      title: message.errorMessage,
      duration: 5000,
      icon: 'none'
    })
  }
  return handled
}

export {
  Http
}

api.js

import { userApis } from './user'

export {
  userApis
}

user.js

import { Http } from './http'

const userApis =  {
  /**
   * 获取用户信息
   */
  async get() {
    return Http.get('/user/get').then((response) => {
      return response && response.data
    })
  },

  /**
   * 更新用户信息
   */
  async update(params) {
    return Http.post('/user/update', params).then((response) => {
      return response && response.data
    })
  }
}

export {
  userApis
}

constants.js

const storageKeys = {
  token: 'accesstoken'
}

export {
  storageKeys
}

config.js

const config = {
  apiBaseUrl: 'https://xxx/api/v1'
}

module.exports.config = config;

util.js

const promisify = function (func) {
  return function (params = {}) {
    return new Promise((resolve, reject) => {
      func({
        ...params,
        success: resolve,
        fail: reject
      })
    })
  }
}

/**
 * 格式化日期
 *
 * @param {*} date 日期
 * @param {*} fmt 格式
 */
const formatDate = (date, fmt) => {
  const properties = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let key in properties) {
    if (new RegExp('(' + key + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? properties[key] : ('00' + properties[key]).substr(('' + properties[key]).length))
    }
  }
  return fmt
}

/**
 * 计算时间戳之间的差值, 以 天,时,分, 秒的结果返回
 *
 * @param start_time 开始时间戳
 * @param end_time 结束时间戳
 */
const calculateDiffTime = (start_time, end_time) => {
  let startTime = 0
  let endTime = 0

  if (start_time < end_time) {
    startTime = start_time
    endTime = end_time
  } else {
    startTime = end_time
    endTime = start_time
  }

  let dateDiff = endTime - startTime
  let dayDiff = parseInt(dateDiff / 1000 / 60 / 60 / 24, 10) // 计算剩余天数
  let hoursDiff = parseInt(dateDiff / 1000 / 60 / 60 % 24, 10) // 计算剩余小时
  let minutesDiff = parseInt(dateDiff / 1000 / 60 % 60, 10) // 计算剩余分钟
  let secondsDiff = parseInt((dateDiff / 1000) % 60, 10) // 计算剩余秒数

  return {
    day: dayDiff < 10 ? '0' + dayDiff : '' + dayDiff,
    hour: hoursDiff < 10 ? '0' + hoursDiff : '' + hoursDiff,
    minute: minutesDiff < 10 ? '0' + minutesDiff : '' + minutesDiff,
    second: secondsDiff < 10 ? '0' + secondsDiff : '' + secondsDiff,
  }
}

module.exports = {
  promisify: promisify,
  formatDate: formatDate,
  calculateDiffTime: calculateDiffTime
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值