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

@chaoswise/request

v1.2.7

Published

公共请求库

Downloads

217

Readme

公共请求库

Features

  • 统一公共请求,作为单独的包运行,相当于axios的再次封装
  • 支持mock数据
  • 多次重复请求,保留最后一次请求(可通过cancelRepeat配置关闭)
  • 封装cancel方法

API

// 全部api引用方法
import {
  initRequest,
  mockInstance,
  axiosInstance,
  clearPending,
  pending,
  fetchGet,
  fetchPut,
  fetchDelete,
  fetchPost,
  upload, 
  downloadFile, 
  formateResponse
} from '@chaoswise/request';

1. initRequest

2. mockInstance

3. axiosInstance

4. clearPending

5. pending

6. fetchGet

7. fetchPut

8. fetchDelete

9. fetchPost

10. upload

11. downloadFile

12. formateResponse


initRequest

初始化配置并创建请求实例axiosInstance

initRequest({
  config: {
    // 请求错误码回调
    statusCallback: {
      '401': () => {
      },
      '403': () => {
      }
    },
    // 是否启用mock数据 false 关闭 true 开启
    useMock: true,
    // mock延迟mm
    delayResponse: 500,
    // 统一处理请求
    handleResponse: (res, error) => {
      if (error) {
        // 错误处理
      } else {
        // 响应处理
      }
    },
    // 是否开启登陆验证 false 关闭 true 开启(统一处理401登出逻辑)
    checkLogin: false,
    // restapi: sso登出校验地址
    restapi: '', // 默认为 error.response.config.url 设置后以设置为准
  },
  // 请求头的配置文件
  defaults: {
    // 请求的基础域名
    baseURL: "",
  },
  // mock模拟请求接口数组, 依赖axios-mock-adapter,约定生成相关mock接口,也可通过mockInstance参考官方api实现mock数据
  mock: [{
    method: 'onGet',
    url: 'mockurl',
    res: {
      code: 100000,
      data: {}
    }
  }]
});

mockInstance

mock数据实例,参考axios-mock-adapter

// 模拟分页接口demo
import { mockInstance } from '@chaoswise/request';
import { demoListData } from './demoListConfig';

mockInstance.onGet("/get/basictablelist").reply((config) => {
  let filterData = demoListData;
  let resultData = [];
  let totalNum = 0;
  let currentPage = config.params.currentPage;
  let pageSize = config.params.pageSize;

  totalNum = filterData.length;
  resultData = filterData.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  return [200, {
    data: resultData,
    total: totalNum
  }];
});

axiosInstance

axios实例,参考axios

// Add a request interceptor
axiosInstance.interceptors.request.use(function (config) {
  // Do something before request is sent
  // 统一增加国际化标识
  config.headers.language = langUtil.getLang().language;
  const isDev = process.env.NODE_ENV === 'development';
  if (window.DOSM_CONFIG.isIgnoreGetway && isDev) {
    config.headers = {
      ...config.headers,
      accountId: '110',
      userId: '2',
      topAccountId: '110',
    };
  }
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

clearPending

中断所有请求

import { clearPending,  fetchPost } from '@chaoswise/request';

// 取消全部已发出请求(例如:页面销毁)
clearPending()

// 指定已请求方法取消
const method1 = fetchPost('/get/list')
method1.cancel();

pending

全部请求根据请求url存储到一个map中,里面包含cancel方法(此方法使用场景不多,大部分场景可以通过clearPending下的场景实现)

import { pending } from '@chaoswise/request';
// 中断某一请求
const cancel = pending.get('/demo/api/v1');
cancel('/demo/api/v1');
pending.delete('/demo/api/v1')

fetchGet

get请求

import { fetchGet } from '@chaoswise/request';

fetchGet('/get/basictablelist', {
  params: {
    name: '张三'
  }
}).then(res => {
  // 成功
}).catch(err => {
  // 失败
})

fetchPut

put请求

import { fetchPut } from '@chaoswise/request';

fetchPut('/get/basictablelist', {
  data: {
    name: '张三'
  }
}).then(res => {
  // 成功
}).catch(err => {
  // 失败
})

fetchDelete

put请求

import { fetchDelete } from '@chaoswise/request';

fetchDelete('/get/basictablelist', {
  data: {
    name: '张三'
  }
}).then(res => {
  // 成功
}).catch(err => {
  // 失败
})

fetchPost

put请求

import { fetchPost } from '@chaoswise/request';

fetchPost('/get/basictablelist', {
  data: {
    name: '张三'
  }
}).then(res => {
  // 成功
}).catch(err => {
  // 失败
})

upload

文件上传

import { upload } from '@chaoswise/request';

upload (
  'http:xxx', // 请求url
  {}, // 请求参数
  () => {}, // 上传进度回调
  {} // 其它请求实例可能要透传的参数
).then(res => {
  // 成功
}).catch(err => {
  // 失败
})

downloadFile

文件下载,默认下载excel

import { downloadFile } from '@chaoswise/request';

downloadFile(
  content, // 内容
  filename, // 文件名称
  {
    type: '下载文件类型'
  }, // 参数
)

formateResponse

  • 后端接口返回数据格式化,
  • 参数response是请求返回值,
  • 将返回值error_code转code,error_msg转msg,
  • 最终返回{code:10000,status:'success',data:null,msg:'**'}
import { formateResponse } from '@chaoswise/request';

const res = formateResponse({
    error_code:000000,
    error_msg:"success",
    data:{}
})

console.log(res);
/*
res = {
    code:100000,
    msg:"success",
    status:"success",
    data:{}
}

mock方法

1. 约定式

在初始化实例进行配置

// 
initRequest({
  mock: [[
    {
      "method": "onGet",
      "url": "/get/list",
      "res": {
          "code": 100000,
          "data": 141314
      }
    },
    {
      "method": "onGet",
      "url": "/get/auth",
      "res": {
          "status": "success",
          "msg": null,
          "code": 100000,
          "data": [
              {
                  "code": "1011000101",
                  "selected": true
              },
              {
                  "code": "11",
                  "selected": true
              }
          ]
      }
    }
  ]]
})

使用mock实例进行注册(具体参考axios-mock-adapter

import { mockInstance } from '@chaoswise/request';

mockInstance.onGet("/get/allUser").reply(200, {
  data: "get 获取的全部用户 [user1, user2, user3]"
});

mockInstance.onPost("/get/allUser").reply(200, {
  data: "post 获取的全部用户 [user1, user2, user3]"
});

mockInstance.onGet("/get/user", {
  params: {
    id: 'user1'
  }
}).reply(200, {
  data: "get 获取的到的用户为: user1"
});

mockInstance.onPost("/get/user", {
  id: 'user1'
}).reply(200, {
  data: "post 获取的到的用户为: user1"
});