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

miniprogram-network

v5.3.0

Published

Redefine the network API of Wechat MiniProgram

Downloads

177

Readme

miniprogram-network npm version

A Network package for MiniProgram

小程序底层网络库封装

Integration

网络库封装

  • [x] Promise泛型Promise
  • [x] CancelToken 可取消操作
  • [x] Retry 网络错误自动重试
  • [x] Cache 底层缓存支持(包括并发请求合并)
  • [x] Timeout 自定义超时时间
  • [x] timestamp 记录请求时间戳
  • [x] 每个请求的原生回调接口支持(onHeadersReceived事件)和(onProgressUpdate事件)
  • [x] Interceptors 拦截器 transform send data / transform response data
  • [x] Listeners 全局事件监听onSend,onResponse,onRejected,onAbort,onComplete
  • [x] 支持全局配置和每个请求单独配置

tips: miniprogram-network >= 5.0.0 底层默认不在直接使用miniprogram-queue进行队列封装, 如果有需要可自行引用, 或直接使用 v4.x

  • wx.request 自基础库 1.4.0 (2017.07) 开始支持队列
  • wx.downloadFile 自基础库 1.4.4 (2017.07) 开始支持队列
  • wx.uploadFile 自基础库 2.4.1 (2018.11) 开始支持队列

安装

npm i miniprogram-network
import {post} from 'miniprogram-network';
post('xxx',data).then(console.log)

配置

通用配置

  • [x] headers 请求头
  • [x] params URL替换参数
  • [x] baseURL 根URL
  • [x] retry 重试次数/自定义重试机制
  • [x] timestamp 是否记录发送和响应时间戳
  • [x] transformSend 输入转换函数(Request,Download,Upload需分别设置)
  • [x] transformResponse 输出转换函数 (Request,Download,Upload需分别设置)

不同网络请求单独配置项

缓存配置

全局缓存策略 cacheConfig

  • [x] cacheConfig.expire 缓存时间单位ms 默认 10分钟
  • [x] cacheConfig.excludeMethod string[] 不缓存的操作,默认['POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT']
  • [x] cacheConfig.resultCondition结果缓存条件,默认isOkResult(2xx)
  • [x] cacheConfig.keyBuilder 缓存key生成规则,修改后excludeMethod将失效

单个请求设置缓存

  • [x] expire 缓存时间单位ms 默认 使用全局配置

transform 数据转换

默认的transformResponse直接返回小程序原始的返回数据{statusCode,...}

同时提供了根据状态码返回对应数据的转换方式

import {
    REQUEST, transformRequestResponseOkData,
    DOWNLOAD, transformDownloadResponseOkData,
    UPLOAD, transformUploadResponseOkData,
} from 'miniprogram-network';

// Request的默认响应拦设为成transformRequestResponseOkData,
// 正常2xx返回data部分,否则rejected
REQUEST.Defaults.transformResponse = transformRequestResponseOkData;
// Download的默认响应拦设为transformDownloadResponseOkData,
// 正常2xx返回string,否则rejected
DOWNLOAD.Defaults.transformResponse = transformDownloadResponseOkData;
// Upload默认响应拦截transformUploadResponseOkData,
// 与小程序wx.uploadFile 不同之处会尝试进行JSON.parse反序列化字符串
// 正常2xx返回data,否则rejected
UPLOAD.Defaults.transformResponse = transformUploadResponseOkData;

DOWNLOAD.download('url')
    .then(path=>{
        console.log(path);//string
    }).catch(res=>{
        console.error(res);//objct
    });

// 参数绑定
Network.put('items/{id}',data,{
        params: {id:123456}, // Object绑定模板参数
    }).then(console.log)
Network.put('items/{0}',data,{
        params: [123456], // 数组绑定模板参数
    }).then(console.log)

取消操作 CancelToken (abort)

可通过cancel token 方式取消请求

import { get, CancelToken } from 'miniprogram-network';

// 创建一个 tokensource
const source = CancelToken.source();

get('items', { skip: 100 }, { 
    // 配置 cancelToken
    cancelToken: source.token 
});

// 需要取消操作时
source.cancel('cancel the get');

快速配置 setConfig

import { setConfig } from 'miniprogram-network';

//将Request,Upload,Download的默认baseURL设置为'https://api.newfuture.cc'
setConfig('baseURL', 'https://api.newfuture.cc');

//等效方式
setConfig({
    baseURL:'https://api.newfuture.cc'
})

延时重试 delayRetry

import { delayRetry,REQUEST } from 'miniprogram-network';

// 间隔1s再次重试,最多重试2次
REQUEST.Defaults.retry = delayRetry(1000,2);

Cache 缓存

  • cacheRequest,cacheGetREQUEST公用默认配置
  • cacheDownloadDOWNLOAD公用默认配置
import {
    cacheConfig, // 缓存配置
    cacheGet, // 与get方法一致,自动使用cache
    cacheDownload, // 与download方法一致,自动使用cache
    cacheRequest, // 与request方法一致,自动使用cache
    } from 'miniprogram-network';

cacheConfig.expire = 10*60*1000;//设置缓存有效时间
// 设置缓存条件,默认响应状态为2xx缓存数据
cacheConfig.resultCondition = function(res){
    return res.statusCode === 200;
}

//cacheGet 与 Request共用配置
cacheGet('xxx').then(resolve);
cacheGet('xxx').then(resolve);

// cacheDownload 与 Download共用配置
cacheDownload('xxx').then();

LifeCycle

详情说明miniprogram-network-life-cycle