@ckpack/fetch-helper
Advanced tools
Comparing version 0.0.7 to 0.1.1
{ | ||
"name": "@ckpack/fetch-helper", | ||
"version": "0.0.7", | ||
"description": "Fetch simple wrapper helper", | ||
"private": false, | ||
"version": "0.1.1", | ||
"description": "一个轻量级的工具函数库", | ||
"sideEffects": false, | ||
"repository": "https://github.com/ckpack/lib", | ||
"author": "chenkai", | ||
"license": "MIT", | ||
"type": "module", | ||
"main": "es/index.js", | ||
"module": "es/index.js", | ||
"types": "es/index.d.ts", | ||
"keywords": [ | ||
"fetch" | ||
], | ||
"repository": "https://github.com/ckpack/fetch-helper", | ||
"types": "./esm/index.d.ts", | ||
"main": "./esm/index.js", | ||
"exports": { | ||
".": "./esm/index.js", | ||
"./*": "./*" | ||
}, | ||
"packageManager": "pnpm@7.9.3", | ||
"dependencies": {}, | ||
"scripts": { | ||
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", | ||
"build": "npm run build:es && npm run build:min", | ||
"build:es": "rm -rf ./es/* && tsc", | ||
"build:min": "rm -rf ./dist/* && npm run build:min:es && npm run build:min:iife", | ||
"build:min:es": "esbuild ./src/index.ts --bundle --minify --format=esm --outfile=./dist/index.es.js", | ||
"build:min:iife": "esbuild ./src/index.ts --bundle --minify --format=iife --global-name=fetchHelper --outfile=./dist/index.iife.js --footer:js=\"fetchHelper = fetchHelper.default;\"", | ||
"lint": "eslint . --ext .js,.ts --fix", | ||
"prepare": "husky install", | ||
"test": "vitest", | ||
"coverage": "vitest run --coverage", | ||
"release": "standard-version", | ||
"prepare": "husky install" | ||
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore", | ||
"build": "tsc && npm run build:min", | ||
"build:min": "rm -rf ./dist/* && npm run build:min:esm && npm run build:min:cjs && npm run build:min:iife", | ||
"build:min:esm": "esbuild ./src/index.ts --bundle --minify --format=esm --outfile=./dist/index.mjs", | ||
"build:min:cjs": "esbuild ./src/index.ts --bundle --minify --format=cjs --outfile=./dist/index.cjs", | ||
"build:min:iife": "esbuild ./src/index.ts --bundle --minify --format=iife --global-name=fetchHelper --outfile=./dist/index.js --footer:js=\"fetchHelper = fetchHelper.default;\"" | ||
}, | ||
"files": [ | ||
"dist", | ||
"es", | ||
"src" | ||
"src", | ||
"esm", | ||
"dist" | ||
], | ||
"author": "ckvv", | ||
"license": "MIT", | ||
"devDependencies": { | ||
"@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.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.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.3" | ||
"husky": "^8.0.1", | ||
"standard-version": "^9.5.0", | ||
"lint-staged": "^13.0.3", | ||
"eslint": "^8.23.0", | ||
"@antfu/eslint-config": "0.26.3", | ||
"@types/node": "18.7.14", | ||
"typescript": "^4.8.2", | ||
"vitest": "0.23.1", | ||
"@vitest/coverage-c8": "0.23.1", | ||
"esbuild": "0.15.7" | ||
}, | ||
"engines": { | ||
"node": ">=18.0.0" | ||
}, | ||
"lint-staged": { | ||
"*.{js,jsx,ts,tsx}": [ | ||
"eslint . --ext .js,.ts --fix" | ||
"*.{js,ts,mjs,cjs,tsx,jsx,vue}": [ | ||
"eslint --fix" | ||
] | ||
}, | ||
"dependencies": {} | ||
} | ||
} |
250
README.md
@@ -1,5 +0,5 @@ | ||
# fetch-helper | ||
# @ckpack/fetch-helper | ||
<h4 align="center"> | ||
<a href="/README-ZH.md">中文</a> | ||
<a href="/README-EN.md">Chinese</a> | ||
| | ||
@@ -9,65 +9,182 @@ <a href="/README.md">ENGLISH</a> | ||
`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. | ||
`@ckpack/fetch-helper` is a lightweight wrapper for the [Fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/fetch) API. It needs to be used in a browser that supports `Fetch` API or `Node.js` (version less than v18.0.0). | ||
````js | ||
import fetch from 'node-fetch'; | ||
globalThis.fetch = fetch; | ||
```` | ||
> 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 | ||
## API Documentation | ||
### fetchHelper | ||
### fetchHelper<T=Response>(input: RequestInfo, init?: FetchHelperInit | undefined): Promise<T> | ||
> Promise<Response> fetchHelper(input[, init]); | ||
+ `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 | ||
+ `baseURL`: this value will be prepended to `input` unless `input` is an absolute address or not a `string` | ||
+ `init`: a configuration item object, including all the settings for the request, supports all the configuration item parameters of the native [fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/fetch) , and added the following parameters | ||
+ `baseURL`: if the passed in `input` is not an absolute address, the value will be prepended to `input`, | ||
+ `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. | ||
+ `paramsSerializer`: set custom serializer `params` parameter function | ||
+ `transformRequest`: allows changing request parameters before the request is made | ||
+ `transformResponse`: allows changing response data after request response | ||
+ `adapter`: Allows custom handling of 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 | ||
Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) object, the default is [`Response`](https://developer. mozilla.org/en-US/docs/Web/API/Response) type, other types can also be returned through `transformResponse` | ||
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. | ||
````js | ||
```js | ||
import fetchHelper from '@ckpack/fetch-helper'; | ||
fetchHelper('/sub-url', { | ||
baseURL: 'https://example.com', | ||
// equal to fetch('http://jsonplaceholder.typicode.com/comments?id=1') | ||
fetchHelper('/comments', { | ||
baseURL: 'http://jsonplaceholder.typicode.com', | ||
params: { | ||
foo: 'bar', | ||
id: 1, | ||
}, | ||
}); | ||
// => fetch('https://example.com/sub-url?foo=bar') | ||
```` | ||
``` | ||
### create(init]) | ||
### fetchHelper.create | ||
Create a new `fetchHelper` instance with custom configuration. | ||
```js | ||
const instance = fetchHelper.create({ | ||
// You can also set other parameters here | ||
baseURL: 'http://jsonplaceholder.typicode.com', | ||
}); | ||
``` | ||
### fetchHelper.default | ||
Permanently modify the request instance configuration via the `default` attribute: | ||
```js | ||
instance.default.baseURL = 'http://localhost:3000' | ||
``` | ||
### fetchHelper[method] | ||
For convenience, aliases are provided for all supported request methods. | ||
```js | ||
fetchHelper.request(config) | ||
fetchHelper.get(url, params?, config?) | ||
fetchHelper.head(url, params?, config?) | ||
fetchHelper.options(url, params?, config?) | ||
fetchHelper.connect(url, params?, config?) | ||
fetchHelper.trace(url, params?, config?) | ||
fetchHelper.delete(url, body?, config?) | ||
fetchHelper.post(url, body?, config?) | ||
fetchHelper.put(url, body?, config?) | ||
fetchHelper.patch(url, body?, config?) | ||
``` | ||
## example | ||
### Set the requested configuration | ||
> create(defaultConfig?: FetchHelperInit) | ||
You can use the `create` method to create an instance with a default config object | ||
````js | ||
```js | ||
import fetchHelper from '@ckpack/fetch-helper'; | ||
const fetchInstance = fetchHelper.create({ | ||
method: 'GET', | ||
mode: 'cors', | ||
transformResponse(response) { | ||
return response.json(); | ||
const instance = fetchHelper.create({ | ||
// You can also set other parameters here | ||
baseURL: 'http://jsonplaceholder.typicode.com', | ||
}); | ||
// fetch('http://jsonplaceholder.typicode.com/comments?id=1') | ||
instance(`/comments`, { | ||
params: { | ||
id: 1, | ||
}, | ||
}); | ||
fetchInstance(`some url`); | ||
```` | ||
// Permanently modify the configuration via the default property | ||
// fetch('http://localhost:3000/comments?id=1') | ||
instance.default.baseURL = 'http://localhost:3000' | ||
instance(`/comments`, { | ||
params: { | ||
id: 1, | ||
}, | ||
}); | ||
## example | ||
// Temporarily modify the configuration by parameters | ||
// fetch('http://localhost:3000/comments?id=1') | ||
await instance(`/comments`, { | ||
baseURL: 'http://localhost:3000', | ||
params: { | ||
id: 1, | ||
}, | ||
}); | ||
``` | ||
### Convert the returned result to `json` | ||
### set request `method` | ||
````js | ||
const fetchHelper = fetchHelper(`some url`, { | ||
You can set the request method through the `method` parameter, such as `GET`, `POST` | ||
```js | ||
await fetchHelper('http://jsonplaceholder.typicode.com/posts', { | ||
method: 'POST', | ||
headers: { | ||
'Content-type': 'application/json', | ||
}, | ||
body: JSON.stringify({ firstName: 'Fred', lastName: 'Flintstone' }), | ||
}); | ||
// or | ||
await fetchHelper.post('http://jsonplaceholder.typicode.com/posts', JSON.stringify({ firstName: 'Fred', lastName: 'Flintstone' }), { | ||
headers: { | ||
'Content-type': 'application/json', | ||
}, | ||
}); | ||
``` | ||
### set query string params | ||
Set the query string (query string), the parameter is serialized and spliced after `url` | ||
```js | ||
// equal to fetch('http://jsonplaceholder.typicode.com/comments?limit=10&page=2&ids=1%2C2%2C3') | ||
fetchHelper('/comments', { | ||
baseURL: 'http://jsonplaceholder.typicode.com', | ||
params: { | ||
limit: 10, | ||
page: 2, | ||
ids: [1,2,3] // ids=1,2,3 | ||
}, | ||
}); | ||
``` | ||
### paramsSerializer | ||
`paramsSerializer` is an optional function responsible for serializing `params`, by default `new URLSearchParams(params).toString()` is used to complete serialization | ||
```js | ||
// equal to fetch('http://jsonplaceholder.typicode.com/comments?limit=10&page=2&ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3') | ||
fetchHelper('/comments', { | ||
baseURL: 'http://jsonplaceholder.typicode.com', | ||
params: { | ||
limit: 10, | ||
page: 2, | ||
ids: [1,2,3] // ids[]=1&ids[]=2&ids[]=3 | ||
}, | ||
paramsSerializer: (params) => Qs.stringify(params, {arrayFormat: 'brackets'}, | ||
}); | ||
``` | ||
### transformRequest | ||
The request parameter configuration can be changed through `transformRequest`. By default, `fetch` passes parameters through `application/json` and requires manual serialization of `JSON.stringify(body)`, and then set `Content-type` in `Headers` to `application` /json`, you can simplify this way with `transformRequest` | ||
```js | ||
const resuest = fetchHelper.create({ | ||
baseURL: 'http://jsonplaceholder.typicode.com', | ||
transformRequest(init){ | ||
const { body } = init; | ||
if(typeof body === 'object' && !(body instanceof FormData || body instanceof URLSearchParams)) { | ||
const headers = new Headers(init.headers) | ||
headers.set('Content-type', 'application/json') | ||
init.headers = headers | ||
init.body = JSON.stringify(body) | ||
} | ||
return init; | ||
}, | ||
}); | ||
const res = await resuest.post('/posts', { firstName: 'Fred', lastName: 'Flintstone' }) | ||
``` | ||
### Transform the request result via `transformResponse` | ||
```js | ||
const fetchHelper = fetchHelper(`http://jsonplaceholder.typicode.com/comments`, { | ||
transformResponse(response) { | ||
@@ -77,20 +194,19 @@ return response.json(); | ||
}); | ||
// The returned result will be converted to json | ||
```` | ||
// The request result will be converted to json | ||
``` | ||
### Set the request's `baseURL` | ||
````js | ||
const fetchInstance = fetchHelper.create({ | ||
baseURL: 'http://some.url', | ||
```ts | ||
// If TypeScript is used, generic types can be specified | ||
const fetchHelper = fetchHelper<{id: number}[]>(`http://jsonplaceholder.typicode.com/comments`, { | ||
transformResponse(response) { | ||
return response.json(); | ||
}, | ||
}); | ||
// fetchHelper[0].id | ||
``` | ||
fetchInstance('/sub-url'); | ||
// => http://some.url/sub-url | ||
```` | ||
### Set request `timeout` | ||
````js | ||
const fetchInstance = fetchHelper.create({ | ||
```js | ||
const instance = fetchHelper.create({ | ||
transformRequest(config) { | ||
@@ -100,3 +216,3 @@ if(config.timeout){ | ||
config.signal = controller.signal; | ||
setTimeout(()=> {controller.abort()}, config.timeout) | ||
setTimeout(()=> controller.abort('timeout'), config.timeout) | ||
} | ||
@@ -107,17 +223,25 @@ return config; | ||
fetchInstance('some url', { | ||
await instance('http://jsonplaceholder.typicode.com/comments', { | ||
timeout: 6000, | ||
}); | ||
// automatically cancel the request after six seconds | ||
```` | ||
``` | ||
### Custom `adapter` | ||
````js | ||
const res = await fetchHelper('https://jsonplaceholder.typicode.com/comments', { | ||
adapter: () => ({ id: 1 }), | ||
```js | ||
const fetchResponse = await fetchHelper(`http://jsonplaceholder.typicode.com/comments`, { | ||
params: { | ||
limit: 1, | ||
page: 2 | ||
}, | ||
adapter(input){ | ||
return new Response(`${input}`); | ||
}, | ||
}); | ||
// return the result directly without fetch => { id: 1 } | ||
```` | ||
For more examples, please refer to [`@ckpack/fetch-helper`](./__test__/index.test.js) | ||
console.log(await fetchResponse.text()) | ||
// Return the result directly without fetching: http://jsonplaceholder.typicode.com/comments?limit=1&page=2 | ||
``` | ||
For more examples, please refer to [`@ckpack/fetch-helper`](./__test__) |
@@ -1,17 +0,51 @@ | ||
import type { FetchHelperInit } from './fetch-helper'; | ||
import { FetchHelper } from './fetch-helper'; | ||
import type { FetchHelperInit, FetchHelperInput, RequestParams } from './FetchHelper.js' | ||
import { FetchHelper, WITHOUT_BODY_METHODS, WITH_BODY_METHODS } from './FetchHelper.js' | ||
export * from './FetchHelper.js' | ||
function createInstance(defaultConfig?: FetchHelperInit) { | ||
const context = new FetchHelper(defaultConfig); | ||
const instance:typeof context.request & { | ||
create?: typeof createInstance | ||
} = context.request.bind(context); | ||
const defaultConfig: FetchHelperInit = {} | ||
export type WithoutBodyMethod = <T=Response>(input: FetchHelperInput, params?: RequestParams | Object, options?: FetchHelperInit) => Promise<T> | ||
export type WithBodyMethod = <T=Response>(input: FetchHelperInput, body?: BodyInit | Object, options?: FetchHelperInit) => Promise<T> | ||
export type InputBodyMethod = <T=Response>(options: FetchHelperInit & { | ||
input: FetchHelperInput | ||
}) => Promise<T> | ||
export const createInstance = (defaultConfig?: FetchHelperInit) => { | ||
const context = new FetchHelper(defaultConfig) | ||
const instance = context.request.bind(context) as typeof context.request & { | ||
create: typeof createInstance | ||
request: InputBodyMethod | ||
get: WithoutBodyMethod | ||
head: WithoutBodyMethod | ||
options: WithoutBodyMethod | ||
connect: WithoutBodyMethod | ||
trace: WithoutBodyMethod | ||
delete: WithBodyMethod | ||
patch: WithBodyMethod | ||
post: WithBodyMethod | ||
put: WithBodyMethod | ||
default: FetchHelperInit | ||
} | ||
instance.default = defaultConfig || {} | ||
instance.create = (createConfig?: FetchHelperInit) => createInstance({ | ||
...defaultConfig, | ||
...instance.default, | ||
...createConfig, | ||
}); | ||
return instance; | ||
}) | ||
WITHOUT_BODY_METHODS.map(val => val.toLowerCase() as Lowercase<typeof val>).forEach((value) => { | ||
instance[value] = (input, params, options) => instance(input, { ...defaultConfig, params, method: value, ...options }) | ||
}) | ||
WITH_BODY_METHODS.map(val => val.toLowerCase() as Lowercase<typeof val>).forEach((value) => { | ||
instance[value] = (input, body: any, options) => instance(input, { ...defaultConfig, body, method: value, ...options }) | ||
}) | ||
instance.request = options => instance(options.input, { ...defaultConfig, ...options }) | ||
return instance | ||
} | ||
export default createInstance(); | ||
const instance = createInstance(defaultConfig) | ||
export default instance |
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No repository
Supply chain riskPackage does not have a linked source code repository. Without this field, a package will have no reference to the location of the source code use to generate the package.
Found 1 instance in 1 package
No repository
Supply chain riskPackage does not have a linked source code repository. Without this field, a package will have no reference to the location of the source code use to generate the package.
Found 1 instance in 1 package
25176
10
12
229
243
5