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

i-apify

v0.6.9

Published

A api solution for `web browser` based Fetch api!

Downloads

24

Readme

apify

A api solution for web browser based Fetch api!

Build Status npm Github All Releases codecov

api.method(payload, option);

Description

基于fetch api的前端数据链路层封装,可以达到一次配置随意轻松使用!

apify 提供了以下功能

  • requset用于发送请求支持POSTGET 请求, PUTDELETE需要自己扩展
  • apify 用于把配置处理为可以发送请求的函数化列表
  • 可以使用apify处理过的简单发送请求方式,也可以直接用requset发送请求
  • i-apify 使用了fetch Api的polyfill,可以直接使用 Headers 和 Response 类

Define


import {apify, request} from 'i-apify';

let list = {
    getUser: '/api/v1/getUser',
    getCity: '/api/method/getCity?type=normal'
};

export default apify(request.post, list, <option>);

Usage

request 对象

request的post,get出了配合apify使用外均可以独立使用。


import {request} from 'i-apify';

request.post('/api/v1/getUser', payload, <option>);
request.get('/api/method/getCity?type=normal', payload, <option>);

apify处理后的函数使用

|参数|说明|default| |---|----|----| |payload| {Object string} | null | |option|{Object=}|{}|

1. 直接使用


api.getUser({
    id: ${userId},
    name: ${userName}
})
    .then(response => {
        // do something
    })
    .catch();

2. 使用local option覆盖global option

api.getCity(null, <option>)
    .then()
    .catch();

Option

默认option及初始值

|参数|default|说明|Fetch API 参数| |---|----|----|----| |method|POST|请求方式|Y| |credentials|include|默认可以跨域请求|Y| |headers|'Accept': 'application/json' 'Content-Type':'application/json'|数据类型JSON|Y| |dataType|json|收发数据类型json|N| |x-timeout|5000ms|超时时间|N| |x-silent|false|用于在hook或handler控制loading是否静默|N| |x-message|true|用于在hook或handler控制是否展示异常等逻辑,可以配合ui-dialog。|N|

全局配置与局部配置

可以使用apify的option来配置所有方法,

let option = {
    'x-timeout': 1000 * 10
};

apify(request.post, list, option);

发送请求时可以对当前方法进行最终配置


api.getUser(null, {
    timeout: 1000 * 6,
    dataType: 'formData' // formdata需要在payload handler中支持
})
    .then()
    .catch();
import {apify, request} from 'i-apify';

let list = {
    getUser: '/api/v1/getUser',
};

let option = {
    hook: {
        beforeRequest({option}) {
            if (!option['x-silent']) {
                ui.loading.show();
            }
        },
        requestSuccess(data) {
            if (!option['x-silent']) {
                ui.loading.hide();
            }
        }
    },
    handler: {
        success(data, option) {

        },
        error(error, option) {
            if (option['x-message']) {
                ui.alert(error.message);
            }
        }
    }
};

let api = apify(request.post, list, option);

// 请求时会有loading,错误会弹窗提示
api.getUser(null)
    .then()
    .catch();

// 局部配置会覆盖全局配置
// 请求时不会有loading,错误不会弹窗提示
api.getUser(null, {
    'x-silent': true,
    'x-message': false,
})
    .then()
    .catch();

通过apify, 或者api.method的option参数可以使用所有fetch api的配置参数。

fetch option

关于fetch api, 可以通过option直接支持fetch api的配置。 Fetch api


let option = {
    method: 'GET',
    mode: 'cors',
    cache: 'default' 
};

// global

apify(request.post, list, option);

// local
api.getUser(payload, option);

hook

通过hook函数可以对请求流程进行精细控制

hook fetch进程钩子函数

|函数名|调用阶段| |----|----| |beforeRequest(option)|发送请求前执行| |timeout(option)|超时时执行| |requestSuccess(option, response)|请求成功后执行| |afterParse(option, data)|解析fetch的response后执行| |requestFail(option, error)|请求失败后执行|

handler 请求后数据处理函数

使用handler可以对请求成功或者失败后对所所获取的数据或逻辑进行最后处理

|参数|说明| |----|----| |data|通过fetch api所获得的数据| |option|请求时使用的最终配置|

handler配置


import {apify, request} from 'i-apify';

let list = {
    getUser: '/api/v1/getUser',
};

let option = {
    handler: {
        success(result, option) {
            // 可以在这里把数据处理成自己想要对格式
        },
        error(data, option) {
            // 可以在这里把数据处理成自己想要对格式
            return data;
        },
        payload(data, option) {
            // 可以在这里对fetch的option 进行处理
            /* global cleenDeep */

            return cleenDeep(data);
        }
    }
}

export default apify(request.post, list, option);

配合async awiat 使用

let option = {
    handler: {
        success(data, option) {
            // 可以在这里对response在进行细分
            if (data) {
                return Promise.resolve(data);
            }
            
            return Promise.reject([1, 2, 3]);
        }
    }
}

async function () {
    try {
        await api.getUser();
    }
    catch({data}) {
        console.log(data) // [1, 2, 3]
    }
}

fetch 默认支持的参数

'method',        // GET/POST等
'headers',       // 一个普通对象,或者一个 Headers 对象
'body',          // 传递给服务器的数据,可以是字符串/Buffer/Blob/FormData,如果方法是 GET/HEAD,则不能有此参数
'mode',          // cors / no-cors / same-origin, 是否跨域,默认是 no-cors
'credentials',   // omit / same-origin / include
'cache',         // default / no-store / reload / no-cache / force-cache / only-if-cached
'redirect',      // follow / error / manual
'referrer',      // no-referrer / client / 或者一个url
'referrerPolicy',// no-referrer / no-referrer-when-downgrade / origin /  origin-when-cross-origin / unsafe-url
'integrity'      // 资源完整性验证

Building & Testing

Building

    npm run build

testing

    npm run test

License MIT