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

@ourea/fetch

v1.2.15

Published

easy to use fetch lib

Downloads

20

Readme

@ourea/fetch

安装

$ npm install @ourea/fetch --save

使用

import Http, { HttpError } from '@ourea/fetch'

const http = Http(opt)

初始化配置


const options = {
  config?: {
    baseUrl: String, // 请求的前置 url,仅对相对路径做拼接
    timeout: Number, // 超时时间 单位 ms
    credentials: String, // fetch 的验证规则配置
    headers: Object<key|value>, // 请求头配置
  },
  before?: (Function | Promise)[], // 前置钩子
  after?: (Function | Promise)[], // 后置后盖
  error?: Function | Promise, // 全局请求错误的错误钩子
  wrapperFunc?: Function, // 对于特殊请求的包裹函数 不推荐使用
  allow?: String[] // 允许使用的方法
}

| 配置 | 说明 | 默认值 | 其它 | | - | - | - | - | | allow | client 允许的请求类型 | ['get', 'post', 'put', 'delete', 'upload', 'download'] | 可选 | | before | 前置钩子(钩子数组) | []| 可选 | | after | 后置钩子(钩子数组) | [] | 可选 | | config | fetch配置项 | | 参考fetch api 文档 | | error | 全局错误处理函数 | null | 可选 |

方法

  • get(url, [params], [options]) // 基于初始化配置的 allow
  • post(url, [params], [options]) // 基于初始化配置的 allow
  • put(url, [params], [options]) // 基于初始化配置的 allow
  • delete(url, [params], [options]) // 基于初始化配置的 allow
  • upload(url, [params], [options]) // 基于初始化配置的 allow
  • download(url, [params], [options]) // 基于初始化配置的 allow
  • setOption(option) 设置请求配置
  • setErrorHook(func) 设置全局错误处理器
  • injectBefore(func) 增加前置拦截器
  • injectAfter(func) 增加后置拦截器

内置错误码

  • HTTP_STATUS_ERROR - 服务器未正常响应
  • REQUEST_TIMEOUT - 请求超时
  • TOKEN_EXPIRE - token校验失败
  • RESPONSE_PARSING_FAILED - response 解析出错
// 使用场景
import Http, { HttpError } from '@ourea/fetch'

// error hook 的返回值 将作为最终的错误体抛出到具体的业务端,在此处可以对error 进行具体的业务性质错误封装
http.setErrorHook(async (httpError, fetchUrl) => {
  if (httpError.code === HttpError.ERROR_CODE.HTTP_STATUS_ERROR) {
    const { msg, error, error_description } = await httpError.response.json()
    return new HttpError({
      message: msg | error_description | error,
      code: httpError.httpStatus,
      httpStatus: httpError.httpStatus,
    })
  }
  console.log('[HTTP ERROR]', fetchUrl, httpError)
})

前/后置钩子

前置钩子

  • 前置钩子的参数为 { url, opt },返回值也必须为{ url, opt }或者无返回
  • 如果需要走错误处理可以直接抛出错误 throw new Error('find error in before hook .')

示例

  http.injectBefore(({ url, opt }) => {
    const { headers, params } = opt
    const token = 'XXXXXXXX'
    const auth = 'xxxxxxxx'

    headers['Authorization'] = `Basic ${auth}`
    headers['Token'] = `${token}`

    return { url, opt: { ...opt, headers }}
  })

后置钩子

  • 后置钩子只有在请求码为200的情况下才会执行,非200的请求则直接跳转到errorHook
  • 钩子的参数为response,若钩子函数返回的是HttpError的实例的话,当前请求的promise会被reject, 这次请求的失败信息将也会触发onError事件
  • 若某一个钩子返回了HttpError则后续的钩子则不会执行
  http.injectAfter(rsp => {
    try {
      const { success, code, message, msg } = rsp

      if (!success || code === 40101) {
        if (code === 40101) { // 根据项目判断状态码
          return new HttpError({
            code,
            httpStatus: HttpError.ERROR_CODE.TOKEN_EXPIRE, // 登录超时
            message: message || msg || HttpError.HTTP_ERROR_MAP[HttpError.ERROR_CODE.TOKEN_EXPIRE],
          })
        } else if (code !== 0) {
          return new HttpError({
            code,
            httpStatus: CUSTOM_HTTP_ERROR_STATUS, // 服务器返回的错误
            message: message || msg || '后台返回未知错误',
          })
        }
      }
    } catch (error) {
      return new HttpError({
        code: CUSTOM_HTTP_ERROR_STATUS,
        httpStatus: HttpError.RESPONSE_PARSING_FAILED, // 解析数据错误
        message: HttpError.HTTP_ERROR_MAP[HttpError.ERROR_CODE.RESPONSE_PARSING_FAILED],
      })
    }
  })

例子

http.injectAfter(function(rsp){
  // do some response check

  return new vFetch.HttpError({
    code: '001',
    message: 'error test',
    httpStatus: null,
  })
})

HttpError

构造函数

HttpError 实例的构造函数为 http.HttpError

示例

...
throw new http.HttpError({
  code: "TOKEN_EXPIRE"
  httpStatus: 401
  message: "用户认证失败"
})
...

整体示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="../dist/vFetch.js"></script>
</head>
<body>
  <script>
    console.log(window, VFetch.HttpError, VFetch.HTTP_ERROR_MAP, VFetch.httpConfig)
    const http = VFetch(VFetch.httpConfig)

    http.injectAfter(function(rst){
      console.log('injectAfter', rst)
      return new vFetch.HttpError({
        code: '001',
        message: 'error test',
        httpStatus: null,
      })
    })

    http.injectAfter(function(){
      console.log(222);
    })

    http.setErrorHook(async function(e){
      console.log(e, 'error');
      const timeoutPromise = new Promise(resolve => setTimeout(() => {
        resolve('async hook')
      }, 1000))
      const data = await timeoutPromise
      console.log(data)
    })

    http.get('t.json', {a:2, c:3}, { baseUrl, headers, timeout, ... })
      .then(rst => {
        //console.log(rst, 'success');
      }).catch(e => {
        //console.log(e, 'error');
      })
  </script>
</body>
</html>