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

@no-996/axios-api

v1.0.6

Published

Api request structured tool builder.

Downloads

43

Readme

axios-api

@no-996/axios-api基于 axios 可建立结构化实例的工具,有以下特点:

  1. 基于 axios,兼容 axios 的 api,可无缝的迁移使用。
  2. 内置了两种常用的请求终止(基于cancelToken)场景,可防止接口重复调用。
  3. 内置了接口调用的缓存机制,在设置的有效期内,可从缓存中获得历史请求结果。
  4. 内置了接口地址模板插入功能,满足基于 url 包含变量值的场景。
  5. 关键:通过结构化的 api 定义生成结构化的 api 请求实例,在项目中畅快的快速调用业务接口。配套使用 webpack 插件(@no-996/axios-api-webpack-plugin),可以自动生成 d.ts 声明文件,在 IDE 中可以获得 api 定义的提醒信息。

第一次生成d.ts文件后,vscode可能需要重启才能显示请求示例的调用提示!

目录

安装使用

npm install --save @no-996/axios-api
// src/api/index.js
import ApiModule from '@no-996/axios-api'
import options from './options'

export default new ApiModule(
  // 接口定义
  options,
  // axios配置
  {
    baseURL: 'https://jsonplaceholder.typicode.com',
    onUploadProgress: (progressEvent, percentCompleted) => {
      console.log(percentCompleted)
    },
  },
  // axios-api配置
  {
    cacheStorage: localStorage,
    debug: true,
  }
)
import instance from './api'
// 即可根据结构化的实例进行调用,如:
// instance.module001.request()
// instance.module001.sub.request()
// instance.module002.request()
// ...

结构化的api定义

// src/api/options/index.js
export default [
  {
    name: 'posts',
    des: '帖子',
    url: '/posts',
    params: {
      userId: undefined,
    },
    children: [
      {
        name: 'comments',
        des: '评论',
        url: '/posts/{postId}/comments',
        urlParams: {
          postId: undefined,
        },
        metadata: {
          urlParams: {
            postId: {
              name: '帖子id',
              required: true,
            },
          },
        },
      },
    ],
    metadata: {
      params: {
        userId: {
          name: '用户id',
          des: '用户唯一标识',
          type: 'string',
        },
      },
    },
  },
  {
    name: 'albums',
    url: '/albums',
    des: '专辑',
    params: {
      id: undefined,
    },
    children: [],
  },
  {
    name: 'photos',
    url: '/photos',
    des: '相片',
    params: {},
    children: [],
    cache: 3000,
  },
  {
    name: 'todos',
    url: '/todos',
    des: '待办事项',
    params: {},
    children: [],
    cancel:'current'
  },
  {
    name: 'users',
    url: '/users',
    des: '用户',
    params: {},
    children: [],
    cancel:'previous'
  },
]

结构化的api请求实例

通过结构化的 api 定义生成结构化的 api 请求实例,在项目中畅快的快速调用业务接口。

生成d.ts声明文件

配套使用webpack插件(@no-996/axios-api-webpack-plugin),根据结构化定义,可以自动生成 d.ts 声明文件,在 IDE 中可以获得 api 定义的提醒信息:

没有定义metadata:

一层:

image image

二层:

image image

调用提示:

image

定义了metadata:

调用提示:

image image

关于上述示例

示例使用Vue,并把请求实例挂载至Vue.prototype上:

// src/App.vue
import Vue from 'vue'
import instance from './api'
// ...
Vue.prototype.$api = instance
// ...

注意,示例中如此挂载到Vue.prototype,需要补充针对Vue.prototype声明,参考如下:

tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    "declaration": true,
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}
src/@types/vue.d.ts
import Vue from 'vue'
import api from '@/api/index'
declare module 'vue/types/vue' {
  interface Vue {
    $api: typeof api
  }
}

请求中止cancel

cancel: 'current'

保留当前正在进行的请求,中止后面重复的请求。

image

cancel: 'previous'

放弃之前的请求,保留最新提交的请求。

image

缓存cache

cache: 3000

3秒内不再request请求,从缓存中获取历史返回结果。

image

接口定义配置说明

|配置|类型|必填|默认值|说明| | :-: | :-: | :-: | :-: | --- | |baseURL|string/function/Promise|否|''|原baseURL的扩展,支持function/Promise返回| |onUploadProgress|(progressEvent: any, percentCompleted: number) => void|否|/|原onUploadProgress的扩展,增加第二参数,返回百分比值| |name|string|是|/|接口名| |des|string|否|/|接口描述| |cancel|'current'/'previous'|否|/|请求中止方式| |cache|number|否|/|接口结果缓存时长毫秒数| |urlOnly|boolean|否|/|是否仅返回处理好的url地址(融合params、urlParams)| |urlParams|object|否|/|url地址模板替换映射| |metadata|ApiMetadata|否|/|请求参数的元数据描述,用于d.ts生成并产生智能提示| |children|array<api配置>|否|[]|api配置嵌套| |interceptors|参考<拦截器>|否|/|局部 axios 拦截器,会替换掉全局 axios 拦截器|

/**
 * 参数元数据内容 / Params metadata info
 */
interface ApiMetadataItem {
  /**
   * 参数名
   * / field name
   */
  name: string
  /**
   * 参数描述
   * / field des
   */
  des: string
  // TODO: 参数校验
  /**
   * 参数类型
   * / field type
   */
  type?: string
  /**
   * 参数必填
   * / field required
   */
  required?: boolean
  /**
   * 自定义校验
   * / field validator
   */
  // validator?:
}

/**
 * 参数元数据 / Params metadata
 */
interface ApiMetadata {
  [index: string]: ApiMetadataItem | string
}

axios-api配置说明

|配置|类型|默认值|说明| | :-: | :-: | :-: | --- | |debug|boolean|false|是否显示调试日志| |cacheStorage|CacheStorage|/|缓存工具(如:localStorage、sessionStorage)| |interceptors|参考<拦截器>|否|/|全局 axios 拦截器|

interface CacheStorage {
  // 获取缓存
  getItem(key: string): string | null
  // 设置缓存
  setItem(key: string, value: string): void
}

拦截器

interceptors?: {
  request?: {
    onFulfilled?: (value: AxiosRequestConfig) => AxiosRequestConfig | Promise<AxiosRequestConfig>
    onRejected?: (error: any) => any
  }
  response?: {
    onFulfilled?: (value: AxiosResponse) => AxiosResponse | Promise<AxiosResponse>
    onRejected?: (error: any) => any
  }
}

依赖说明

"dependencies": {
  "@types/md5": "2.3.1",
  "@types/qs": "6.9.7",
  "@types/uuid": "8.3.4",
  "axios": "0.24.0",
  "md5": "2.3.0",
  "qs": "6.7.0",
  "uuid": "8.3.2"
}

版本日志

v1.0.6

Add default options for request function.

v1.0.5

Fix some syntax error when use typescript.

v1.0.4

Enable options assign.

v1.0.3

Add global and instance interceptors setting.

v1.0.2

Expose axiosInstance.

v1.0.1

Update publish files.

v1.0.0

First release version.