npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

weapp-backend-api

v0.0.13

Published

统一封装微信小程序平台后端接口的调用

Downloads

28

Readme

weapp-backend-api

NPM version changelog license

npm-image

统一封装微信小程序平台后端接口的调用

  • 集中配置接口
  • 统一发送请求(requestuploadFile)
  • 统一处理请求的返回
  • 统一适配请求返回的数据格式
  • 统一异常处理
  • Promise 风格
    • sendRequest(name, options, namespace).then
  • 支持日志级别参数, 用于在调试阶段输出每个请求的信息
  • 预留扩展点(继承覆盖的方式)
    • beforeSend(requestOptions) 发送请求前的统一处理, 如果返回一个 Promise 可以阻止发送请求
    • afterSend(requestOptions, requestResult) 请求结束后的统一处理
    • normalizeRequestResult(requestOptions, requestResult) 标准化接口返回的数据格式, 方便适配各种接口返回数据格式不同的情况
    • failStatusHandler(requestOptions, requestResult) 针对错误状态做自定义处理
    • commonFailStatusHandler(requestOptions, requestResult) 当接口处理失败时通用的错误状态处理
    • commonFailTip(requestOptions, requestResult) 接口出错时统一弹出错误提示信息
    • getFailTipMessage(requestOptions, requestResult) 获取给用户的错误提示

调用后端接口的统一流程

准备

  • 配置接口的参数(apiConfig 中的)
  • 配置接口的默认参数(defaultRequestOptions 中的)
  • 组装接口的参数(合并默认的参数/配置的参数/本次请求的参数)

发送

  • 发送请求前的统一处理
    • 查找请求队列拦截重复请求(不发送请求)
    • 查找接口缓存数据, 如果存在则直接返回缓存数据(不发送请求)
    • 显示 loading 提示
  • 发送 HTTP 请求(具体平台具体实现)
    • 将请求加入到请求队列
  • 请求结束后的统一处理
    • 将请求从请求队列中移除
    • 关闭 loading 提示

完成

安装

npm install weapp-backend-api --save

使用 APIDoc

import BackendApi from 'weapp-backend-api';
import Logger from 'simple-console-log-level';

var backendApi = new BackendApi({
    'getList': {
        method: 'GET',
        url: 'https://domain.com/list'
    },
    'getUser': { // RESTful
        method: 'GET',
        url: 'https://domain.com/user'
    },
    'uploadPhoto': { // wx.uploadFile
        _type: 'uploadFile',
        url: 'https://domain.com/photo/upload'
    }
}, undefined, Logger.LEVEL_WARN);

// 调用配置好的接口
backendApi.sendRequest('getList', {
    // wx.request options
}).then(function([data]) {
    console.log(data);
}, function(requestResult) {
    console.log(requestResult);
});

// 调用没有配置的接口
backendApi.sendRequest('', {
    url: 'https://domain.com/foobar'
}).then(function([data]) {
    console.log(data);
}, function(requestResult) {
    console.log(requestResult);
});

// 支持 RESTful 风格
backendApi.sendRequest('getUser/1', {
    // wx.request options
}).then(function([data]) {
    console.log(data);
}, function(requestResult) {
    console.log(requestResult);
});

// 支持上传文件
backendApi.sendRequest('uploadPhoto', {
    filePath: '', // 例如通过 wx.chooseImage 拿到的文件路径
    name: 'file'
}).then(function([data]) {
    console.log(data);
}, function(requestResult) {
    console.log(requestResult);
});

// 支持 namespace 机制, 便于拆分接口配置
backendApi.addApiConfig('user', {
    getInfo: {
        url: 'https://domain.com/user/info'
    }
});
// 显式指定 namespace
backendApi.sendRequest('getInfo', {
    // wx.request options
}, 'user').then(function([data]) {
    console.log(data);
}, function(requestResult) {
    console.log(requestResult);
});
// 直接拼上 namespace 更简洁
backendApi.sendRequest('user.getInfo', {
    // wx.request options
}).then(function([data]) {
    console.log(data);
}, function(requestResult) {
    console.log(requestResult);
});

// 支持加载远程的接口配置, 之后的接口调用会在接口配置加载完成后才真正发送
backendApi.loadApiConfig({
    url: 'https://domain.com/api-config/abc123'
});
backendApi.sendRequest('getProject', {
    // wx.request options
}).then(function([data]) {
    console.log(data);
}, function(requestResult) {
    console.log(requestResult);
});

实现的自定义请求参数(options)

  • _showLoading 默认发送请求时会显示一个正在加载中的提示
  • _showLoadingMask 默认发送请求时不开启加载中的蒙层
  • _showFailTip 默认请求失败时会给用户提示错误消息
  • _showFailTipDuration 接口调用出错时错误信息显示多长的时间(ms), 默认为 wx.showToast 默认的显示时长
  • _interceptDuplicateRequest 是否拦截重复请求, 默认不拦截重复请求
  • _cacheTtl 缓存接口返回的数据, 设置缓存数据的存活时长(ms)
  • _normalizeRequestResult 适配单个接口返回的数据以符合标准的接口数据格式
  • _type 请求的类型, 默认通过 request 来发送请求, 如果是上传文件, 请设置为 uploadFile

核心逻辑流程

  • 配置接口 - new BackendApi(apiConfig)
  • 发送请求 - sendRequest
    • 获取调用接口的配置 - _getRequestOptions
    • 发送 HTTP 请求 - $sendHttpRequest
      • 发送请求前的统一处理 - beforeSend
        • 拦截重复请求 - _interceptDuplicateRequest
        • 获取接口缓存 - cachedRequestResult
        • 显示 loading 提示 - _showLoading
      • 发出请求 - wx.request
      • 将请求放入到发送中的队列 - _addToSending
      • 判断 HTTP 请求是否成功 - statusCode
      • 请求结束后的统一处理 - afterSend
        • 将请求从发送中的队列中移除 - _removeFromSending
        • 关闭 loading 提示 - _hideLoading
      • 请求成功 - _successHandler
        • 标准化接口的返回数据 - _normalizeRequestResult -> normalizeRequestResult
        • 判断接口调用是否成功 - _ifApiSuccess
          • 成功: 将请求结果写入缓存 - _cacheTtl
          • 失败: 通用的错误处理 - commonFailStatusHandler
      • 请求失败 - _failHandler
        • 标准化请求失败的数据并规范错误码
        • 通用的错误处理 - commonFailStatusHandler
          • 输出错误日志
          • 针对错误状态做自定义处理 - failStatusHandler
          • 抛出错误提示给用户 - commonFailTip <- getFailTipMessage