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

api-mock-handler

v1.0.0

Published

基于 [axios](https://github.com/axios/axios) 和 [mockjs](https://github.com/nuysoft/Mock) 的 API 控制工具.

Downloads

2

Readme

AMH

基于 axiosmockjs 的 API 控制工具.

功能

  • 基于 API 定义生成请求代理.
  • 提供全局、命名空间、接口三种层级的 mock 控制.
  • 允许自定义所使用的请求库,默认为 axios.
  • 允许为请求自定义发起方法.

安装

使用 npm:

$ npm install api-mock-handler

使用

创建实例

import amh from 'api-mock-handler'

const instance = amh.create({
    interface: {
        user: {
            mock: true,
            baseURL: '/api/user',
            login: {
                url: '/login',
                method: 'post'
            },
            logout: {mock: false}
        }
    },
    mock: true,
    mocker: {
        user: {
            login ({body}) {
                // this 指向 mockjs 实例
                const {username} = JSON.parse(body)
            	return {code: 200, msg: '', data: {username}}
            }
        }
    }
})

此时 instance 将会代理如下两个接口:

[{
  	url: '/api/user/login',
    method: 'post',
    mock: true
  }, {
   	url: '/api/user/logout',
    method: 'get',
    mock: false
  }]

调用接口

instance.user.login({
    data: {username: 'admin'}
}).then(res => res.data)
    .then(data => {
    console.dir(data)
})

// {code: 200, msg: '', data: {username: 'admin'}}

instance.user.logout()
 .catch(error => console.error(error))
// 

该接口将会被 mock ,而模拟数据的产生由 mocker.user.login 函数定义。

创建实例的参数

{
    interfaces: object, // 必填
    mock: boolean, // 选填,默认为 false,
    mocker: object, // 选填,当 mock 为 true 时必填
    requester: function, // 选填,请求发起库,默认为 axios
    onRequest: function, // 选填
    concatPath: function, // 选填,定义路径解析行为
    debug: boolen, // 选填,默认为 false
}
  • interfaces 接口列表,由全局 baseURL 与一组命名空间组成:

    {
        baseURL: string, // 选填,作为域名部分与后面接口路径进行拼接
        [...namespace]
    }

    命名空间,由 baseURLmock与一组接口组成:

    {
        baseURL: string, // 选填,默认为命名空间的名字,与接口路径进行拼接
        mock: boolean, // 选填,默认为 false,当设为 true 时,此命名空间下的所有 mock 属性未被显式设为 false 的接口都将打开 mock 开关
        [...interface]
    }

    接口,组成:

    {
        url: string, // 选填,默认为接口的名字
        mock: boolean, // 选填,默认为 false,接口是否需要 mock 以此属性的显式设置值为准
        method: string, // 选填,接口的请求方式,默认为 get
        meta: object, // 选填,接口的一些元信息
    }
  • mock 用于声明是否开启 mock 功能。

  • mocker 若某个命名空间中某个接口设置了 mock 参数为 true,则需要在此参数中设置同命名空间、同接口名的处理函数,否则会报错。

  • requester 发起请求的请求库,默认为 axios。

  • onRequest 定义如何发起请求,函数签名为:

    (config, args, requester) => {}

    对于调用(下称 call):

    instance.user.login({data: {username: 'admin'}})

    onRequest 函数响应如下:

    (config, args, requester) => {
        /**
         * config: {
         *   url: '/api/user/login',
         *   method: 'post',
         *   meta: {}
         * }
         * 
         * args: [{
         *   data: {username: 'admin'}
         * }]
         *
         * requester: axios (未设置 requester 的情况下)
         */
        return {} // 此函数返回结果即为 call 的返回结果
    }
  • concatPath 默认的路径拼接行为:

    (baseURL, url) => url[0] === '/' ? `${baseURL}${url}` : `${baseURL}/${url}`
  • debug 开启后,将会在以下情形输出一些信息:

    • 没有为命名空间设置 baseURL

      Warn: The namespace [${namespace}] does not set baseURL!
    • 提示你为某个命名空间打开了 mock 开关

      Info: You turned on the mock option for the namespace [${namespace}]
    • 成功为某个接口绑定了 mock 处理函数

      Info: Bind the mock function for interface [${namespace}.${_interface_name_}]

当发生以下情况时将会报错:

  • 开启了全局 mock 却未提供 mocker

    You have enabled mock mode but don't provide mocker.
  • 为某个接口开启了 mock 却没有在 mocker 中提供相应的处理函数

    You turned on the mock option for interface [${namespace}.${_interface_name_}] but did not provide the corresponding handler in the mocker.
  • 当你尝试使用一个不存在的命名空间时

    The definition of namespace [${namespace}] could not be found.
  • 当你尝试使用一个不存在的接口时

    The definition of interface [${namespace}.${_interface_name_}] could not be found.

注意事项

关于 Mockjs

  • 此工具的 mock 功能由 mockjs 实现,因此请不要在项目中自行引入 mockjs,否则会导致 mockjs 重复创建 xhr 的代理,导致死循环。

  • 可以通过 amh.Mock 获取 mockjs 实例。