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

wxapp-api-interceptors

v1.4.3

Published

微信小程序api拦截封装

Downloads

19

Readme

微信小程序api拦截器

  • 完美兼容原生小程序项目
  • 完美兼用小程序api的原本调用方式,无痛迁移
  • 小程序api全Promise化
  • 和axios一样的请求方式
  • 小程序api自定义拦截调用参数和返回结果
  • 强大的async拦截

快速开始

安装

npm install wxapp-api-interceptors --save

使用

mpvue等项目
import wxApiInterceptors from 'wxapp-api-interceptors';

wxApiInterceptors(); // 必须在调用小程序api之前调用
原生小程序和taro项目

下载该项目,解压移动文件夹distwxApiInterceptors.jsruntime.js文件到你自己的项目,详见示例

const wxApiInterceptors = require('./wxApiInterceptors');

wxApiInterceptors(); // 必须在调用小程序api之前调用

小程序api调用

不必传success、complete和fail参数。

函数式异步调用方式:
wx.showLoading({title: '登录中...'})
    .then(wx.login)
    .then(data => wx.request.post('/login', {data}))
    .then(() => wx.showToast({title: '登录成功'}))
    .catch(() => wx.showToast({title: '登录失败'}))
    .finally(wx.hideLoading);
也兼容原生的调用方式(不便维护):
wx.showLoading({
    title: '登录中...',
    success: () => {
        wx.login({
            success: (data) => {
                wx.request({
                    url: '/login',
                    data,
                    success: () => wx.showToast({title: '登录成功'}),
                    fail: () => wx.showToast({title: '登录失败'}),
                    complete: wx.hideLoading,
                });
            },
        });
    },
});

自定义拦截器

使用方法及参数:wxApiInterceptors({[api]: {[request](params):params, [response](res):res}}, [isReturn]: boolean)

比如拦截wx.showModal的confirmColor默认值为red,调用成功后并拦截调用成功返回的结果。

wxApiInterceptors({
    showModal: {
        request(params) {
            if (params.confirmColor === undefined) {
                params.confirmColor = 'red';
            }
            return params;
        },
        response(res) {
            res = '调用成功';
            return res;
        },
    }
});

wx.showModal({title: '测试'})
    .then(console.log);
// 控制的输出:调用成功

默认拦截了request api,封装成了和axios差不多的使用方式

调用wx.request[method](url, [config])发送axios化的请求。

默认GET请求
wx.request('https://test.com/banner')
    .then(({data}) => {
        console.log(data);
    })
其他请求方式
wx.request.post('https://test.com', {data: {userName: 'test'}})
    .then(({data}) => {
        console.log(data);
    })

当然也可以再继续拦截request api

比如设置request api默认的host:

wxApiInterceptors({
    request: {
        request(params) {
            const host = 'https://test.com'
            if (!/^(http|\/\/)/.test(params.url)) {
                params.url = host + params.url;
            }
            return params;
        },
    },
});

甚至可以拦截自己的业务状态码:

wxApiInterceptors({
    request: {
        response(res) {
            const {data: {code}} = res;
            // 如果data里的code等于-1就响应为失败
            if (code === -1) {
                return Promise.reject(res);
            }
            return res;
        },
    },
});

强大的async拦截器

比如调用request api的时候都在header里带上本地储存的token,没有的话从服务器获取:

wxApiInterceptors({
    request: {
        async request(params) {
            if (params.header === undefined) {
                params.header = {};
            }
            let token = wx.getStorageSync('token');
            if (!token) {
                ({data: token} = await wx.request('/getToken'));
                wx.setStorageSync('token', token);
            }
            params.header.token = token;
            return params;
        },
    },
});

原生小程序项目使用async需要特殊处理,请看示例

小程序基础版本2.0.8后的小程序,在后台配置了插件不能直接调用全局wx对象issues,需要在调用wxApiInterceptors({}, true)时传入第二个参数为true,会返回一个代理后的对象以供调用,请看示例