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

@lichao.franklee/ajax

v1.0.1

Published

一个规范Ajax使用的框架

Downloads

3

Readme

@lx-frontend/ajax

一个规范Ajax使用的框架

安装

使用npm:

npm install @lx-frontend/ajax

使用yarn:

yarn add @lx-frontend/ajax

浏览器全局引入:

将dist/index.min.js文件复制到项目中,在html中引入脚本。

<script src="/path/to/index.min.js"></script>

该脚本暴露了Ajax类,使用时还需进一步实例化。

Example

// 请求库实例
import axios from 'axios';
import Ajax from '@lx-frontend/ajax';

// rest配置
const rest = {
  firstModule: {
    getCall: ['get', '/the/request/url', requestOptions],
    postCall: ['post', '/the/post/url', requestOptions]
  }
}

// 实例化配置
const options = {
  rest,
  requestInstance: axios
}

// 实例化
const ajax = new Ajax(options)

完成Ajax实例化之后,即可使用如下方式发起请求:

ajax.$rest.firstModule.getCall().then(res => {/***/})

ajax.$rest.firstModule.postCall(data).then(res => {/***/})

options配置

// const ajax = new Ajax(options)
{
  requestInstance
  rest
  baseUrl
  extension
  isProduction
  requestInterceptor
  responseOkInterceptor
  responseErrorInterceptor
  responseNotOkHandler
  errorReporter
  schema
  handleRequestDataInvalid
  handleResponseDataInvalid
}

requestInstance

请求库的实例,目前支持axios和flyio。

注意这里传入的是请求库的实例对象,而不是类。请求库在不同的场景下有不同的实例化方式,具体请参考axios和flyio文档。

rest

该框架要求所有请求必须属于一个模块,rest对象的每个属性则代表一个模块,模块下是具体的请求函数配置。

rest的配置遵循如下模式:

{
  moduleName: {
    funcName: [method, url, requestOptions]
    // ...
  }
  // ...
}

例如: 如下rest配置中,firstModule是模块名称,该模块下有两个名为getCallpostCall的请求

const rest = {
  firstModule: {
    getCall: ['get', '/the/request/url'],
    postCall: ['post', '/the/post/url']
  }
}

rest的结构决定了Ajax在实例化之后的调用方式,比如,getCallpostCall将通过如下方式调用:

// const ajax = new Ajax(options)
// 实例化之后,请求函数组成的模块将被挂载到 $rest 属性下
ajax.$rest.firstModule.getCall().then(/***/)
ajax.$rest.firstModule.postCall().then(/***/)

请求配置 [method, url, requestOptions]

模块下具体的请求通过一个三元数组配置而来,数组项分别表示:请求的方法,请求的路径,以及对请求的配置。

method: string类型,目前仅支持get, put, post, patch, delete方法

url: string类型,该路径将和requestOptions的baseUrl属性拼接,组成最终的请求路径。

requestOptions: object, 详见requestOptions

requestOptions

{
  isReturnRes // Boolean,true表示直接返回response,false表示返回response.data
  baseUrl // 请求路径前缀,拼接在url之前,构成一个完整的请求路径
  cache // Boolean,该请求是否开启缓存,可选,默认false
  dataType // json/form, POST、DELETE、PATCH、PUT请求提交数据的格式(JSON或者FromData)
  // ...
}
isReturnRes: boolean

default: false

请求完成后,是否返回完整的response对象给业务代码处理。

默认false,表示请求完成后,会获取response的data属性,然后将data返回给业务逻辑。

baseUrl: string

default: ''

请求路径前缀,baseUrl + url共同构成请求的完整路径。

Ajax实例化参数中也有该属性,具体请求上的baseUrl优先级更高,会替换Ajax实例化参数中的同名参数。

dataType: json/form

default: 'json'

post,put,patch,delete请求携带数据的格式。

支持两个值:'json' 和 'form'。json表示JSON格式,form表示FormData格式

cache: Boolean

default: false

表示请求是否开启浏览器缓存,默认不开启。

其他参数

requestOptions最终会合并到请求的配置中去,所以,只要是请求库支持的请求配置都可以在这里配置。

baseUrl

请求路径前缀,string类型,该值会和每个请求的url配置合并,构成最终的请求路径。

requestOptions中的baseUrl会覆盖该配置。

extension

用于扩展Ajax实例,该配置下的所有属性都会在Ajax实例化后,挂载到实例对象上。

若Ajax实例化完成后,仍想扩展实例,可以使用实例的extend方法:

// const ajax = new Ajax(options);
ajax.extend({/***/})

isProduction: Boolean or Function

判断当前环境是否是生产环境,用作功能开关,比如信息打印。

requestInterceptor: response => response

请求拦截器处理函数,(config) => config,可选。

对于不同的请求库(axios/flyio),这里的config会有一些差异,具体请查阅请求库文档。

注意:不要使用箭头函数,函数执行上下文(this)指向ajax实例。

responseOkInterceptor: response => response

响应成功拦截器处理函数,response => response, 可选。

注意:不要使用箭头函数,函数执行上下文(this)指向ajax实例。

responseErrorInterceptor: err => any

响应请求错误的拦截器,即status不等于304且不在[200, 300),error => any,可选。

若函数返回Promise.reject(err),错误将由catch捕获,并将错误交给errorReporter处理,最后err也将透传给业务逻辑(注意,业务代码中使用then的成功处理函数接收该值,而不是catch或then的失败处理函数,所以业务逻辑中要判断返回值是否符合要求)。

若函数返回一个值(err),框架根据请求的isReturnRes配置,返回err或者err.data给业务逻辑。如果err.data不存在,则返回undefined。

注意:不要使用箭头函数,函数执行上下文(this)指向ajax实例。

responseNotOkHandler: response => void

请求正常返回,但后端判断请求出错,即status===200 && res.data.code!==0,可选。

这里可以通知用户错误信息,或做其他处理。

errorReporter: err => void

用于上报错误信息,比如上报sentry等。可选。

schema

用于存放请求数据和返回数据校验所需的JSONSchema,配置结构和rest的结构一致。

比如,假如rest的配置如下:

{
  moduleName: {
    funcName: [method, url, requestOptions]
    // ...
  }
  // ...
}

则,如果要校验funcName请求的数据,其配置如下:

{
  moduleName: {
    funcName: {
      requestSchema: /* request data Jsonschema */,
      responseSchema: /* response data Jsonschema */
    }
    // ...
  }
  // ...
}

其中,区别在于,原函数的数组配置项被Jsonschema配置替换。requestSchema和responseSchema是固定属性名,可以不配置,默认通过校验。

handleRequestDataInvalid: (url, message) => void

请求参数校验失败时的处理函数。用户可以决定当请求参数校验失败时做些什么。可选,默认打印两个参数。

函数的第一个参数为请求的url路径,第二个参数是错误信息。

handleResponseDataInvalid: (url, message) => void

返回数据校验未通过时的处理函数。用户自定义,可选,默认打印两个参数。

TODO:如果handleRequestDataInvalid和handleResponseDataInvalid抛出错误,会有什么影响?要怎么处理?

待实现想法:

下一步方向:

  1. 兼容wx原生请求
  2. 自动生成jsonschema
  3. 仅返回最后一次请求的数据