@ckpack/fetch-helper
Advanced tools
Comparing version 0.0.6 to 0.0.7
@@ -1,1 +0,1 @@ | ||
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}; | ||
var o=s=>`${new URLSearchParams(s)}`,c=new RegExp("^(?:[a-z]+:)?//","i"),n=class{baseInit;input;init;constructor(t){this.baseInit=t}async request(t,r){let e={...this.baseInit,...r};this.input=t,this.init=e.transformRequest?await e.transformRequest(e,this):e,this.input=typeof this.input=="string"&&!c.test(`${this.input}`)?`${this.init.baseURL||""}${t}`:this.input;let i=(this.init.paramsSerializer||o)(this.init.params),a=await(this.init.adapter||fetch)(`${this.input}${i&&`?${i}`}`,this.init);return e.transformResponse?e.transformResponse(a,this):a}};function p(s){let t=new n(s),r=t.request.bind(t);return r.create=e=>p({...s,...e}),r}var R=p();export{R as default}; |
@@ -1,2 +0,2 @@ | ||
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);})(); | ||
var fetchHelper=(()=>{var i=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var R=(t,e)=>{for(var r in e)i(t,r,{get:e[r],enumerable:!0})},l=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of h(e))!m.call(t,n)&&n!==r&&i(t,n,{get:()=>e[n],enumerable:!(s=c(e,n))||s.enumerable});return t};var u=t=>l(i({},"__esModule",{value:!0}),t);var H={};R(H,{default:()=>F});var f=t=>`${new URLSearchParams(t)}`,I=new RegExp("^(?:[a-z]+:)?//","i"),a=class{baseInit;input;init;constructor(e){this.baseInit=e}async request(e,r){let s={...this.baseInit,...r};this.input=e,this.init=s.transformRequest?await s.transformRequest(s,this):s,this.input=typeof this.input=="string"&&!I.test(`${this.input}`)?`${this.init.baseURL||""}${e}`:this.input;let n=(this.init.paramsSerializer||f)(this.init.params),p=await(this.init.adapter||fetch)(`${this.input}${n&&`?${n}`}`,this.init);return s.transformResponse?s.transformResponse(p,this):p}};function o(t){let e=new a(t),r=e.request.bind(e);return r.create=s=>o({...t,...s}),r}var F=o();return u(H);})(); | ||
fetchHelper = fetchHelper.default; |
@@ -1,7 +0,13 @@ | ||
import type { RequestMiddleware, ResponseMiddleware } from './compose'; | ||
declare type Params = Record<string, any>; | ||
export declare type TransformRequest = (init?: FetchHelperInit, ctx?: FetchHelper) => Promise<FetchHelperInit> | FetchHelperInit; | ||
export declare type TransformResponse = (response?: Response, ctx?: FetchHelper) => Promise<Response> | Response | any; | ||
declare const paramsSerializer: (params?: Params | undefined) => string; | ||
export declare type ParamsSerializer = typeof paramsSerializer; | ||
export interface FetchHelperInit extends RequestInit { | ||
interceptors?: { | ||
request?: RequestMiddleware[]; | ||
response?: ResponseMiddleware[]; | ||
}; | ||
baseURL?: string; | ||
params?: Params; | ||
paramsSerializer?: ParamsSerializer; | ||
transformRequest?: TransformRequest; | ||
transformResponse?: TransformResponse; | ||
adapter?: (input: RequestInfo, init?: FetchHelperInit) => Promise<Response>; | ||
[index: string]: any; | ||
@@ -16,1 +22,2 @@ } | ||
} | ||
export {}; |
@@ -1,2 +0,3 @@ | ||
import { compose } from './compose'; | ||
const paramsSerializer = (params) => `${new URLSearchParams(params)}`; | ||
const absUrlReg = new RegExp('^(?:[a-z]+:)?//', 'i'); | ||
export class FetchHelper { | ||
@@ -12,6 +13,8 @@ baseInit; | ||
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); | ||
this.init = mergeInit.transformRequest ? await mergeInit.transformRequest(mergeInit, this) : mergeInit; | ||
this.input = (typeof this.input === 'string' && !absUrlReg.test(`${this.input}`)) ? `${this.init.baseURL || ''}${input}` : this.input; | ||
const searchParams = (this.init.paramsSerializer || paramsSerializer)(this.init.params); | ||
const response = await (this.init.adapter || fetch)(`${this.input}${searchParams && `?${searchParams}`}`, this.init); | ||
return mergeInit.transformResponse ? mergeInit.transformResponse(response, this) : response; | ||
} | ||
} |
{ | ||
"name": "@ckpack/fetch-helper", | ||
"version": "0.0.6", | ||
"version": "0.0.7", | ||
"description": "Fetch simple wrapper helper", | ||
@@ -32,19 +32,20 @@ "type": "module", | ||
"devDependencies": { | ||
"@commitlint/cli": "^16.1.0", | ||
"@commitlint/config-conventional": "^16.0.0", | ||
"@types/jest": "^27.4.0", | ||
"eslint": "^8.7.0", | ||
"@ckpack/fetch-helper": "file:./", | ||
"@commitlint/cli": "^16.2.3", | ||
"@commitlint/config-conventional": "^16.2.1", | ||
"@types/jest": "^27.4.1", | ||
"eslint": "^8.11.0", | ||
"eslint-plugin-import": "^2.25.4", | ||
"eslint-config-airbnb-typescript": "^16.1.0", | ||
"@typescript-eslint/eslint-plugin": "^5.10.1", | ||
"@typescript-eslint/parser": "^5.10.1", | ||
"typescript": "^4.5.5", | ||
"esbuild": "^0.14.14", | ||
"eslint-config-airbnb-typescript": "^16.1.3", | ||
"@typescript-eslint/eslint-plugin": "^5.15.0", | ||
"@typescript-eslint/parser": "^5.15.0", | ||
"typescript": "^4.6.2", | ||
"esbuild": "^0.14.27", | ||
"husky": "^7.0.4", | ||
"jest": "^27.4.7", | ||
"lint-staged": "^12.3.2", | ||
"jest": "^27.5.1", | ||
"lint-staged": "^12.3.6", | ||
"standard-version": "^9.3.2", | ||
"ts-jest": "^27.1.3", | ||
"tslib": "^2.3.1", | ||
"node-fetch": "^3.2.0" | ||
"node-fetch": "^3.2.3" | ||
}, | ||
@@ -51,0 +52,0 @@ "lint-staged": { |
107
README.md
@@ -16,6 +16,8 @@ # fetch-helper | ||
>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 | ||
> If you are using a node version greater than `v17.5.0`, you can directly enable the `fetch` API with the --experimental-fetch CLI flag | ||
## parameters | ||
## API Documentation | ||
### fetchHelper | ||
> Promise<Response> fetchHelper(input[, init]); | ||
@@ -25,13 +27,24 @@ | ||
+ `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` | ||
+ `baseURL`: this value will be prepended to `input` unless `input` is an absolute address or not a `string` | ||
+ `params`: URL parameters sent with the request, must be a plain object or a `URLSearchParams` object | ||
+ `paramsSerializer`: allows custom serialization of `params` parameter functions | ||
+ `transformRequest`: allows changing request parameters before | ||
+ `transformResponse`: allows to change response data before | ||
+ `adapter`: allows custom handling of `fetch` requests, which makes testing easier. | ||
>`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 | ||
> `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 | ||
## return value | ||
Returns a [`Response`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) of a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) /en-US/docs/Web/API/Response) object. | ||
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. | ||
````js | ||
import fetchHelper from '@ckpack/fetch-helper'; | ||
## method | ||
fetchHelper('/sub-url', { | ||
baseURL: 'https://example.com', | ||
params: { | ||
foo: 'bar', | ||
}, | ||
}); | ||
// => fetch('https://example.com/sub-url?foo=bar') | ||
```` | ||
@@ -43,10 +56,9 @@ ### create(init]) | ||
````js | ||
fetchHelper.create({ | ||
import fetchHelper from '@ckpack/fetch-helper'; | ||
const fetchInstance = fetchHelper.create({ | ||
method: 'GET', | ||
mode: 'cors', | ||
interceptors: { | ||
response: [(response, config) => { | ||
return response.json(); | ||
}] | ||
} | ||
transformResponse(response) { | ||
return response.json(); | ||
}, | ||
}); | ||
@@ -59,43 +71,36 @@ | ||
### Set request `header` | ||
### Convert the returned result to `json` | ||
````js | ||
fetchHelper(`some url`, { | ||
interceptors: { | ||
request: [(config) => { | ||
config.headers = new Headers({ | ||
'Authorization': localStorage.getItem('token') | ||
}); | ||
return config; | ||
}], | ||
} | ||
const fetchHelper = fetchHelper(`some url`, { | ||
transformResponse(response) { | ||
return response.json(); | ||
}, | ||
}); | ||
// The returned result will be converted to json | ||
```` | ||
### Convert the returned result to `json` | ||
### Set the request's `baseURL` | ||
````js | ||
fetchHelper(`some url`, { | ||
interceptors: { | ||
response: [(response) => { | ||
return response.json(); | ||
}] | ||
} | ||
const fetchInstance = fetchHelper.create({ | ||
baseURL: 'http://some.url', | ||
}); | ||
fetchInstance('/sub-url'); | ||
// => http://some.url/sub-url | ||
```` | ||
### Custom `timeout` | ||
### Set request `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; | ||
}], | ||
transformRequest(config) { | ||
if(config.timeout){ | ||
const controller = new AbortController(); | ||
config.signal = controller.signal; | ||
setTimeout(()=> {controller.abort()}, config.timeout) | ||
} | ||
return config; | ||
}, | ||
}); | ||
@@ -106,18 +111,14 @@ | ||
}); | ||
// automatically cancel the request after six seconds | ||
```` | ||
### custom `baseURL` | ||
### Custom `adapter` | ||
````js | ||
const fetchInstance = fetchHelper.create({ | ||
baseURL: 'http://some.url', | ||
interceptors: { | ||
request: [(config, ctx)=>{ | ||
ctx.input = `${config.baseURL}${ctx.input}`; | ||
return config; | ||
}], | ||
} | ||
const res = await fetchHelper('https://jsonplaceholder.typicode.com/comments', { | ||
adapter: () => ({ id: 1 }), | ||
}); | ||
// return the result directly without fetch => { id: 1 } | ||
```` | ||
fetchInstance('/sub-url'); | ||
```` | ||
For more examples, please refer to [`@ckpack/fetch-helper`](./__test__/index.test.js) |
@@ -1,12 +0,22 @@ | ||
import type { RequestMiddleware, ResponseMiddleware } from './compose'; | ||
import { compose } from './compose'; | ||
type Params = Record<string, any>; | ||
export type TransformRequest = (init?:FetchHelperInit, ctx?: FetchHelper) => Promise<FetchHelperInit> | FetchHelperInit; | ||
export type TransformResponse = (response?: Response, ctx?: FetchHelper) => Promise<Response> | Response | any; | ||
const paramsSerializer = (params?: Params) => `${new URLSearchParams(params)}`; | ||
export type ParamsSerializer = typeof paramsSerializer; | ||
export interface FetchHelperInit extends RequestInit { | ||
interceptors?: { | ||
request?: RequestMiddleware[], | ||
response?: ResponseMiddleware[], | ||
}; | ||
baseURL?: string, | ||
params?: Params, | ||
paramsSerializer?: ParamsSerializer, | ||
transformRequest?: TransformRequest, | ||
transformResponse?: TransformResponse, | ||
adapter?: (input: RequestInfo, init?: FetchHelperInit) => Promise<Response>, | ||
[index: string]: any; | ||
} | ||
const absUrlReg = new RegExp('^(?:[a-z]+:)?//', 'i'); | ||
export class FetchHelper { | ||
@@ -26,6 +36,8 @@ baseInit?: FetchHelperInit; | ||
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); | ||
this.init = mergeInit.transformRequest ? await mergeInit.transformRequest(mergeInit, this) : mergeInit; | ||
this.input = (typeof this.input === 'string' && !absUrlReg.test(`${this.input}`) ) ? `${this.init.baseURL || ''}${input}` : this.input; | ||
const searchParams = (this.init.paramsSerializer || paramsSerializer)(this.init.params); | ||
const response = await (this.init.adapter || fetch)(`${this.input}${searchParams && `?${searchParams}`}`, this.init); | ||
return mergeInit.transformResponse ? mergeInit.transformResponse(response, this) : response; | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
13331
18
11
115