Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@ourea/fetch

Package Overview
Dependencies
Maintainers
2
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ourea/fetch

easy to use fetch lib

  • 1.2.15
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
5
decreased by-16.67%
Maintainers
2
Weekly downloads
 
Created
Source

@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[] // 允许使用的方法
}

配置说明默认值其它
allowclient 允许的请求类型['get', 'post', 'put', 'delete', 'upload', 'download']可选
before前置钩子(钩子数组)[]可选
after后置钩子(钩子数组)[]可选
configfetch配置项参考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>

Keywords

FAQs

Package last updated on 19 Jun 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc