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

uke-request

v1.1.0

Published

基于 fetch API 的 HTTP 请求封装,内置中间件(内置 RC4 数据加解密、LZMA 数据压解缩中间件)机制、RESTFul API 支持。

Downloads

290

Readme

Uke Request

基于 fetch API 的进一步封装, 提供订阅发布与中间件机制。

Build Status install size

Basic Usage

Support RESTFul

以下事例以 $R 指定 RequestClass 的实例

import { RequestClass } from 'uke-request/request';

const $R = new RequestClass();

// 可以为每一个请求对象设置配置
$R.setConfig({
  baseUrl: 'https://example.com', // 默认的请求地址
  commonHeaders: {} // 所有的请求 headers
});

const getRes = await $R.get('/path');
const postRes = await $R.post('/path', {
  ID: '123'
});
const putRes = await $R.put('/path', {
  ID: '123'
});
const delRes = await $R.del('/path', {
  ID: '123'
});

Adavance Usage

把 params 转换成 query url

// get, 使用 params 自动转换成对应的 url
// 最终请求: ${baseUrl}/item-list?id=123&other=123
let res = await $R.get({
  url: '/item-list',
  headers: {},
  params: {
    id: 123,
    other: 321
  },
  isBase64: false // 用于加密 params 的值
});

// 统一的检查 res status 的状态,如果 return false,则触发 onErr
$R.checkStatus = (originRes) => {
  return true;
}

事件订阅

$R 提供两种订阅事件 onRes onErr, 并且会响应每个请求都

// 每当有 res 的时候执行
$R.on('onRes', (resDetail) => {
  resDetail = {
    data: {},
    originRes: {},
    originReq: {},
    err: null
  }
});

// 每当发生错误时执行
$R.on('onErr', (resDetail) => {
  resDetail = {
    data: {},
    originRes: {},
    originReq: {},
    err: errMsg
  }
});

错误触发 & 错误处理

$R 将根据 checkStatus 返回值判断是否进入错误处理流程, 错误处理流程有两种方式

  1. 订阅 $R.on('onErr', function errHandle() {})
  2. 为每一个请求订阅的错误回调 $R.get({ url: '', onError: function errHandle() {} })

注意: 如果传入了 onError 回调,则不执行通过 $R.on('onErr') 订阅的回调

// override checkStatus
$R.checkStatus = (fetchRes: Response): boolean => false

// 如果传入了 onError 回调,则不执行通过 $R.on('onErr') 订阅的回调
$R.get({
  url: '/get-stuff',
  onError: (data) => {
    console.log(data)
  }
})

$R.on('onErr', function errHandle(data) {
  console.log(data)
})

中间件 Middleware

中间件处理有两个触发时机, 一旦注册,则每次请求都会触发,并且原来用于提交的 data 将会被中间件返回的值替换

  1. 请求前 before req
  2. 响应后 after res
const before = (reqData) => {
  return reqData;
}
const after = (resData) => {
  return resData;
}
$R.use([before, after])

let postRes = await $R.post('/item-list', data, options);

内置中间件

通讯加密

import { encrypt, decrypt } from 'uke-request/request-middleware/encrypt-helper';
import { compress, decompress } from 'uke-request/request-middleware/compress-helper';

const encryptKey = '123';

// 使用加密解密
$R.use([encrypt(encryptKey), decrypt(encryptKey)]);

// $R 会将 {ID: '321'} 以 '123' 为加密 key 进行 rc4 加密并发送到服务器
// 收到响应后以同样方式解密,如果服务端返回的数据也时同样方式加密的话
const resPost = await $R.post(testUrl + '/encrypt', {
  ID: '321'
});

// 使用内容压缩
// dataWrapper、dataWrapperBeforeDecompress、dataWrapperAfterDecompress 均为格式调整回调,
interface CompressParams {
  data: {};
  isCompress: boolean;
}

interface DecompressParams {
  data: string;
  isCompress: boolean;
}
const dataWrapper(data: CompressParams): CompressParams => {};
const dataWrapperBeforeDecompress(data: DecompressParams): DecompressParams => {};
const dataWrapperAfterDecompress(data: DecompressParams): DecompressParams => {};

$R.use([
  compress(limitedLen, dataWrapper),
  decompress(dataWrapperBeforeDecompress, dataWrapperAfterDecompress)
]);

// 如果消息体的长度大于 limitedLen,则会将消息进行 lzma 压缩

$R API

interface RequestParams {
  url: string;
  method?: RequestMethod;
  sendType?: RequestSendTypes;
  data: {};
  headers?: {};
  params?: ParamEntity;
  returnRaw?: boolean;
  onError?: Function;
}
interface RequestConfig {
  baseUrl: string;
  commonHeaders: {};
  timeout: number;
  resMark: string;
  errMark: string;
}
interface MiddlewareOptions {
  after?: Function | Function[];
  before?: Function | Function[];
}

// 底层 request API
$R.request(params: RequestParams)

// 设置 $R 配置
$R.setConfig(config: RequestConfig)

// 使用中间件
$R.use(options: MiddlewareOptions | Function[])

// 同 $R.use([before])
$R.useBefore(Function | Function[])

// 同 $R.use([null, after])
$R.useAfter(Function | Function[])

// url 包装
$R.urlFilter(path: string, params?: ParamEntity)

// 上传
$R.upload(path: string, data: RequestInit["body"])

$R.request 为通用底层接口,其他的 $R.get $R.post $R.del $R.put $R.patch 均为该接口的上层应用封装。

// 其他方式, options 同 fetch API,sendData 如果是 js,将自动做 header 对应的转换
let res = await $R.request({
  url, data, headers, method = 'POST',
  returnRaw = false, // 是否返回完整的 res 状态 return returnAll ? res : res.data
  ...other
});

url resolve

uke-request 提供,用于解析前端的 urlAPI

import {
  toBase64Str, fromBase64Str,
  getUrlParams, searchUrlParams, urlParamsToQuery, openWindowUseHashUrl,
  resolveUrl, decodeHashUrl
} from 'uke-request/url-resolve';

urlParamsToQuery

const urlParamsConfig = {
  url: 'https://ss.com',
  params: {
    id: '1',
    req: {
      sessID: 123,
      username: 'alex',
    }
  },
  toBase64: false // 如果为 true,则将值进行 base64 转换
}

urlParamsToQuery(urlParamsConfig); // 输出 'https://ss.com?id=1&req={sessID:123,username=alex}'

getUrlParams

// 若此时的 url 为 'https://ss.com?id=1&req={sessID:123,username=alex}'
const res = getUrlParams(id); // res = 1

resolveUrl

resolveUrl('https://a.com', 'path1', 'path2'); // 输出 'https://a.com/path1/path2'