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

@ckpack/fetch-helper

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ckpack/fetch-helper - npm Package Compare versions

Comparing version 0.0.5 to 0.0.6

2

dist/index.es.js

@@ -1,1 +0,1 @@

function c(n=[]){return(e,t)=>n.reduce(async(r,s)=>s(await r,t),e)}var p=class{defaults;constructor(e){this.defaults=e}async request(e,t){return new Promise(async(r,s)=>{let u={...this.defaults,...t},o=await c(u?.interceptors?.request)(u),i;o.timeout&&(i=setTimeout(()=>{clearTimeout(i),s(new Error(`Timeout(${o.timeout}ms): Fetch ${e}`))},o.timeout));let f=await fetch(e,o);clearTimeout(i),r(await c(o?.interceptors?.response)(f,o))})}};function a(n){let e=new p(n),t=e.request.bind(e);return t.create=r=>a({...n,...r}),t}var y=a();export{y as default};
function i(n,e){return t=>Array.isArray(e)?e.reduce(async(r,s)=>s(await r,n),t):t}var p=class{baseInit;input;init;constructor(e){this.baseInit=e}async request(e,t){let r={...this.baseInit,...t};this.input=e,this.init=await i(this,r?.interceptors?.request)(r);let s=await fetch(this.input,this.init);return i(this,this.init?.interceptors?.response)(s)}};function o(n){let e=new p(n),t=e.request.bind(e);return t.create=r=>o({...n,...r}),t}var l=o();export{l as default};

@@ -1,2 +0,2 @@

var fetchHelper=(()=>{var c=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var y=t=>c(t,"__esModule",{value:!0});var F=(t,e)=>{for(var o in e)c(t,o,{get:e[o],enumerable:!0})},w=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of d(e))!l.call(t,n)&&(o||n!=="default")&&c(t,n,{get:()=>e[n],enumerable:!(r=h(e,n))||r.enumerable});return t};var g=(t=>(e,o)=>t&&t.get(e)||(o=w(y({}),e,1),t&&t.set(e,o),o))(typeof WeakMap!="undefined"?new WeakMap:0);var R={};F(R,{default:()=>C});function p(t=[]){return(e,o)=>t.reduce(async(r,n)=>n(await r,o),e)}var u=class{defaults;constructor(e){this.defaults=e}async request(e,o){return new Promise(async(r,n)=>{let a={...this.defaults,...o},s=await p(a?.interceptors?.request)(a),i;s.timeout&&(i=setTimeout(()=>{clearTimeout(i),n(new Error(`Timeout(${s.timeout}ms): Fetch ${e}`))},s.timeout));let m=await fetch(e,s);clearTimeout(i),r(await p(s?.interceptors?.response)(m,s))})}};function f(t){let e=new u(t),o=e.request.bind(e);return o.create=r=>f({...t,...r}),o}var C=f();return g(R);})();
var fetchHelper=(()=>{var i=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var l=t=>i(t,"__esModule",{value:!0});var I=(t,e)=>{for(var r in e)i(t,r,{get:e[r],enumerable:!0})},F=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of a(e))!u.call(t,s)&&(r||s!=="default")&&i(t,s,{get:()=>e[s],enumerable:!(n=h(e,s))||n.enumerable});return t};var H=(t=>(e,r)=>t&&t.get(e)||(r=F(l({}),e,1),t&&t.set(e,r),r))(typeof WeakMap!="undefined"?new WeakMap:0);var f={};I(f,{default:()=>d});function p(t,e){return r=>Array.isArray(e)?e.reduce(async(n,s)=>s(await n,t),r):r}var o=class{baseInit;input;init;constructor(e){this.baseInit=e}async request(e,r){let n={...this.baseInit,...r};this.input=e,this.init=await p(this,n?.interceptors?.request)(n);let s=await fetch(this.input,this.init);return p(this,this.init?.interceptors?.response)(s)}};function c(t){let e=new o(t),r=e.request.bind(e);return r.create=n=>c({...t,...n}),r}var d=c();return H(f);})();
fetchHelper = fetchHelper.default;

@@ -1,4 +0,4 @@

import type { FetchConfig } from './fetch-helper';
export declare type RequestMiddleware = (fetchConfig: FetchConfig) => FetchConfig;
export declare type ResponseMiddleware = (response: Response, fetchConfig: FetchConfig) => unknown;
export declare function compose(middleware?: any): <T>(params: T, params2?: any) => T;
import type { FetchHelperInit, FetchHelper } from './fetch-helper';
export declare type RequestMiddleware = (init: FetchHelperInit, ctx: FetchHelper) => FetchHelperInit | unknown;
export declare type ResponseMiddleware = (response: Response, ctx: FetchHelper) => Response | unknown;
export declare function compose(ctx: FetchHelper, middleware?: any[]): <T>(params: T) => T;

@@ -1,7 +0,7 @@

export function compose(middleware = []) {
return (params, params2) => {
return middleware.reduce(async (previousValue, currentValue) => {
return currentValue(await previousValue, params2);
}, params);
export function compose(ctx, middleware) {
return (params) => {
return Array.isArray(middleware) ? middleware.reduce(async (previousValue, currentValue) => {
return currentValue(await previousValue, ctx);
}, params) : params;
};
}
import type { RequestMiddleware, ResponseMiddleware } from './compose';
export interface FetchConfig extends RequestInit {
export interface FetchHelperInit extends RequestInit {
interceptors?: {

@@ -7,8 +7,10 @@ request?: RequestMiddleware[];

};
timeout?: number;
[index: string]: any;
}
export declare class FetchHelper {
defaults: FetchConfig | undefined;
constructor(fetchConfig?: FetchConfig);
request(fetchInput: RequestInfo, fetchInit?: FetchConfig): Promise<Response>;
baseInit?: FetchHelperInit;
input?: RequestInfo;
init?: FetchHelperInit;
constructor(fetchConfig?: FetchHelperInit);
request(input: RequestInfo, init?: FetchHelperInit): Promise<Response>;
}
import { compose } from './compose';
export class FetchHelper {
defaults;
baseInit;
input;
init;
constructor(fetchConfig) {
this.defaults = fetchConfig;
this.baseInit = fetchConfig;
}
async request(fetchInput, fetchInit) {
return new Promise(async (resolve, reject) => {
const mergeFetchInit = { ...this.defaults, ...fetchInit };
const composeFetchInit = await compose(mergeFetchInit?.interceptors?.request)(mergeFetchInit);
let timeOut;
if (composeFetchInit.timeout) {
timeOut = setTimeout(() => {
clearTimeout(timeOut);
reject(new Error(`Timeout(${composeFetchInit.timeout}ms): Fetch ${fetchInput}`));
}, composeFetchInit.timeout);
}
const response = await fetch(fetchInput, composeFetchInit);
clearTimeout(timeOut);
resolve(await compose(composeFetchInit?.interceptors?.response)(response, composeFetchInit));
});
async request(input, init) {
const mergeInit = { ...this.baseInit, ...init };
this.input = input;
this.init = await compose(this, mergeInit?.interceptors?.request)(mergeInit);
const response = await fetch(this.input, this.init);
return compose(this, this.init?.interceptors?.response)(response);
}
}

@@ -1,8 +0,8 @@

import type { FetchConfig } from './fetch-helper';
declare function createInstance(defaultConfig?: FetchConfig): ((fetchInput: RequestInfo, fetchInit?: FetchConfig | undefined) => Promise<Response>) & {
import type { FetchHelperInit } from './fetch-helper';
declare function createInstance(defaultConfig?: FetchHelperInit): ((input: RequestInfo, init?: FetchHelperInit | undefined) => Promise<Response>) & {
create?: typeof createInstance | undefined;
};
declare const _default: ((fetchInput: RequestInfo, fetchInit?: FetchConfig | undefined) => Promise<Response>) & {
declare const _default: ((input: RequestInfo, init?: FetchHelperInit | undefined) => Promise<Response>) & {
create?: typeof createInstance | undefined;
};
export default _default;
{
"name": "@ckpack/fetch-helper",
"version": "0.0.5",
"version": "0.0.6",
"description": "Fetch simple wrapper helper",

@@ -5,0 +5,0 @@ "type": "module",

# fetch-helper
`fetch-helper`是对 [fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/fetch) API的简单封装, 所以只支持在浏览器中使用,如果需要在node环境中使用,请添加`fetch-node`依赖。
<h4 align="center">
<a href="/README-ZH.md">中文</a>
|
<a href="/README.md">ENGLISH</a>
</h4>
```js
`fetch-helper` is a lightweight wrapper for the [fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/fetch) API, only supported in browsers, if needed For use in node environment, please add `fetch-node` global dependency.
````js
import fetch from 'node-fetch';
globalThis.fetch = fetch;
```
````
## 参数
>If you are using a node version greater than `v17.5.0`, you can enable the `fetch` API directly with the --experimental-fetch CLI flag
> Promise<Response> fetch(input[, Fetchinit]);
## parameters
`fetch-helper`除了支持原生[fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/fetch)的所有配置项参数还添加了以下参数
> Promise<Response> fetchHelper(input[, init]);
+ `timeout`: `timeout?: number`,超时时间(单位毫秒),默认不设置超时时间
+ `interceptors`: ``, 请求拦截器,该参数包含两个属性
+ `request`: `(fetchConfig: FetchConfig) => FetchConfig []`, 请求触发前触发,你可以用来修改请求参数
+ `response`: `(response: Response, fetchConfig: FetchConfig) => unknown []`, 请求触发后触发,你可以用来修改返回结果
+ `input`: the requested url or [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object
+ `init`: a configuration item object, including all the settings for the request, except all the configuration items that support native [fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/fetch) Parameters also added the following parameters
+ `interceptors`: request interceptors, this parameter contains two attributes
+ `request`: contains an array of type `(init, ctx) => init`, triggered before the request is triggered, you can modify the request parameters by returning a new configuration item object
+ `response`: contains an array of type `(response, ctx) => response`, triggered after the request is triggered, you can use it to modify the returned `response`
如下面是一个获取修改`headers`,并将返回结果转为`json`的例子
>`ctx` is the context of the current request instance, through which you can get or modify the current request's `input`, `init` and other instance parameters
```js
const fetchHelper = FetchHelper(`some url`, {
// fetch配置项所有可选的参数
## return value
A [`Response`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) [`Response`](https://developer.mozilla.org/ en-US/docs/Web/API/Response) object.
## method
### create(init])
You can use the `create` method to create an instance with a default config object
````js
fetchHelper.create({
method: 'GET',
mode: 'cors',
interceptors: {
request: [(config) => {
config.headers = new Headers({
'Authorization': localStorage.getItem('token')
});
return config;
}],
response: [(response, config) => {

@@ -38,14 +50,12 @@ return response.json();

});
```
## 返回值
fetchInstance(`some url`);
````
异步返回一个 [Response](https://developer.mozilla.org/zh-CN/docs/Web/API/Response) 对象。
## example
## 其他
### Set request `header`
你可以使用`create`方法创建一个自定义配置的新实例。
```js
const featch = FetchHelper.create({
````js
fetchHelper(`some url`, {
interceptors: {

@@ -58,3 +68,12 @@ request: [(config) => {

}],
response: [(response, config) => {
}
});
````
### Convert the returned result to `json`
````js
fetchHelper(`some url`, {
interceptors: {
response: [(response) => {
return response.json();

@@ -64,4 +83,39 @@ }]

});
````
featch(`some url`);
```
### Custom `timeout`
````js
const fetchInstance = fetchHelper.create({
interceptors: {
request: [(config)=>{
if(config.timeout){
const controller = new AbortController();
config.signal = controller.signal;
setTimeout(()=> {controller.abort()}, config.timeout)
}
return config;
}],
}
});
fetchInstance('some url', {
timeout: 6000,
});
````
### custom `baseURL`
````js
const fetchInstance = fetchHelper.create({
baseURL: 'http://some.url',
interceptors: {
request: [(config, ctx)=>{
ctx.input = `${config.baseURL}${ctx.input}`;
return config;
}],
}
});
fetchInstance('/sub-url');
````

@@ -1,12 +0,12 @@

import type { FetchConfig } from './fetch-helper';
import type { FetchHelperInit, FetchHelper } from './fetch-helper';
export type RequestMiddleware = (fetchConfig:FetchConfig) => FetchConfig;
export type ResponseMiddleware = (response: Response, fetchConfig:FetchConfig) => unknown;
export type RequestMiddleware = (init:FetchHelperInit, ctx : FetchHelper) => FetchHelperInit | unknown;
export type ResponseMiddleware = (response: Response, ctx : FetchHelper) => Response | unknown;
export function compose(middleware:any = []) {
return <T>(params:T, params2?: any): T => {
return middleware.reduce(async (previousValue: T, currentValue: any) => {
return currentValue(await previousValue, params2);
}, params);
export function compose(ctx : FetchHelper, middleware?: any[]) {
return <T>(params:T): T => {
return Array.isArray(middleware) ? middleware.reduce(async (previousValue: T, currentValue: any) => {
return currentValue(await previousValue, ctx);
}, params) : params;
};
}
import type { RequestMiddleware, ResponseMiddleware } from './compose';
import { compose } from './compose';
export interface FetchConfig extends RequestInit {
export interface FetchHelperInit extends RequestInit {
interceptors?: {
request?: RequestMiddleware[],
response?: ResponseMiddleware[],
},
timeout?: number,
};
[index: string]: any;
}
export class FetchHelper {
defaults: FetchConfig | undefined;
baseInit?: FetchHelperInit;
constructor(fetchConfig?: FetchConfig) {
this.defaults = fetchConfig;
input?: RequestInfo;
init?: FetchHelperInit;
constructor(fetchConfig?: FetchHelperInit) {
this.baseInit = fetchConfig;
}
async request(fetchInput: RequestInfo, fetchInit?: FetchConfig) :Promise<Response> {
return new Promise(async (resolve, reject) => {
const mergeFetchInit = { ...this.defaults, ...fetchInit };
const composeFetchInit = await compose(mergeFetchInit?.interceptors?.request)(mergeFetchInit);
let timeOut!: ReturnType<typeof setTimeout>;
if (composeFetchInit.timeout) {
timeOut = setTimeout(() => {
clearTimeout(timeOut);
reject(new Error(`Timeout(${composeFetchInit.timeout}ms): Fetch ${fetchInput}`));
}, composeFetchInit.timeout);
}
const response = await fetch(fetchInput, composeFetchInit);
clearTimeout(timeOut);
resolve(await compose(composeFetchInit?.interceptors?.response)(response, composeFetchInit));
});
async request(input: RequestInfo, init?: FetchHelperInit) :Promise<Response> {
const mergeInit = { ...this.baseInit, ...init };
this.input = input;
this.init = await compose(this, mergeInit?.interceptors?.request)(mergeInit);
const response = await fetch(this.input, this.init);
return compose(this, this.init?.interceptors?.response)(response);
}
}

@@ -1,5 +0,5 @@

import type { FetchConfig } from './fetch-helper';
import type { FetchHelperInit } from './fetch-helper';
import { FetchHelper } from './fetch-helper';
function createInstance(defaultConfig?: FetchConfig) {
function createInstance(defaultConfig?: FetchHelperInit) {
const context = new FetchHelper(defaultConfig);

@@ -10,3 +10,3 @@ const instance:typeof context.request & {

instance.create = (createConfig?: FetchConfig) => createInstance({
instance.create = (createConfig?: FetchHelperInit) => createInstance({
...defaultConfig,

@@ -13,0 +13,0 @@ ...createConfig,

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