Skip to content

Commit

Permalink
Merge branch 'main' into pr/minht11/320
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed May 16, 2024
2 parents 53de546 + f7f9463 commit f087bf8
Show file tree
Hide file tree
Showing 14 changed files with 4,006 additions and 3,348 deletions.
1 change: 0 additions & 1 deletion .eslintignore

This file was deleted.

8 changes: 0 additions & 8 deletions .eslintrc

This file was deleted.

2 changes: 1 addition & 1 deletion .github/workflows/autofix.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ jobs:
- run: pnpm install
- name: Fix lint issues
run: pnpm run lint:fix
- uses: autofix-ci/action@d3e591514b99d0fca6779455ff8338516663f7cc
- uses: autofix-ci/action@ea32e3a12414e6d3183163c3424a7d7a8631ad84
with:
commit-message: "chore: apply automated fixes"
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node: [16, 18, 20]
node: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- run: corepack enable
Expand All @@ -25,4 +25,4 @@ jobs:
- run: pnpm lint
- run: pnpm build
- run: pnpm vitest --coverage
- uses: codecov/codecov-action@v3
- uses: codecov/codecov-action@v4
45 changes: 45 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,51 @@

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

## v1.3.4

[compare changes](https://github.com/unjs/ofetch/compare/v1.3.3...v1.3.4)

### 🚀 Enhancements

- Export all types ([#280](https://github.com/unjs/ofetch/pull/280))
- Expose `GlobalOptions` type ([#307](https://github.com/unjs/ofetch/pull/307))

### 🩹 Fixes

- Clear abort timeout after response was received ([#369](https://github.com/unjs/ofetch/pull/369))

### 💅 Refactors

- Remove extra line ([#374](https://github.com/unjs/ofetch/pull/374))

### 📖 Documentation

- Add initial examples ([#288](https://github.com/unjs/ofetch/pull/288))

### 📦 Build

- Add top level `react-native` field ([03680dd](https://github.com/unjs/ofetch/commit/03680dd))

### 🏡 Chore

- **release:** V1.3.3 ([31c61c1](https://github.com/unjs/ofetch/commit/31c61c1))
- Update dependencies ([308f03f](https://github.com/unjs/ofetch/commit/308f03f))
- Ignore conflicting ts error for now ([3a73165](https://github.com/unjs/ofetch/commit/3a73165))
- Improve docs ([173d5b9](https://github.com/unjs/ofetch/commit/173d5b9))
- Remove lagon ([#346](https://github.com/unjs/ofetch/pull/346))
- Update lockfile ([4b6d1ba](https://github.com/unjs/ofetch/commit/4b6d1ba))
- Fix build error ([472c4d9](https://github.com/unjs/ofetch/commit/472c4d9))
- Update node-fetch-native ([fa2cc07](https://github.com/unjs/ofetch/commit/fa2cc07))

### ❤️ Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))
- Alex Liu ([@Mini-ghost](http://github.com/Mini-ghost))
- Danila Rodichkin ([@daniluk4000](http://github.com/daniluk4000))
- Maxime Pauvert ([@maximepvrt](http://github.com/maximepvrt))
- Estéban ([@Barbapapazes](http://github.com/Barbapapazes))
- Saman <[email protected]>

## v1.3.3

[compare changes](https://github.com/unjs/ofetch/compare/v1.3.2...v1.3.3)
Expand Down
69 changes: 43 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
[![License][license-src]][license-href]
[![JSDocs][jsdocs-src]][jsdocs-href]

A better fetch API. Works on node, browser and workers.
A better fetch API. Works on node, browser, and workers.

## 🚀 Quick Start

Expand Down Expand Up @@ -38,21 +38,21 @@ and automatically use [unjs/node-fetch-native](https://github.com/unjs/node-fetc

### `keepAlive` support

By setting the `FETCH_KEEP_ALIVE` environment variable to `true`, an http/https agent will be registered that keeps sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection.
By setting the `FETCH_KEEP_ALIVE` environment variable to `true`, an HTTP/HTTPS agent will be registered that keeps sockets around even when there are no outstanding requests, so they can be used for future requests without having to re-establish a TCP connection.

**Note:** This option can potentially introduce memory leaks. Please check [node-fetch/node-fetch#1325](https://github.com/node-fetch/node-fetch/pull/1325).

## ✔️ Parsing Response

`ofetch` will smartly parse JSON and native values using [destr](https://github.com/unjs/destr), falling back to text if it fails to parse.
`ofetch` will smartly parse JSON and native values using [destr](https://github.com/unjs/destr), falling back to the text if it fails to parse.

```js
const { users } = await ofetch("/api/users");
```

For binary content types, `ofetch` will instead return a `Blob` object.

You can optionally provide a different parser than destr, or specify `blob`, `arrayBuffer` or `text` to force parsing the body with the respective `FetchResponse` method.
You can optionally provide a different parser than `destr`, or specify `blob`, `arrayBuffer`, or `text` to force parsing the body with the respective `FetchResponse` method.

```js
// Use JSON.parse
Expand Down Expand Up @@ -86,9 +86,9 @@ const { users } = await ofetch("/api/users", {

## ✔️ Handling Errors

`ofetch` Automatically throw errors when `response.ok` is `false` with a friendly error message and compact stack (hiding internals).
`ofetch` Automatically throws errors when `response.ok` is `false` with a friendly error message and compact stack (hiding internals).

Parsed error body is available with `error.data`. You may also use `FetchError` type.
A parsed error body is available with `error.data`. You may also use `FetchError` type.

```ts
await ofetch("https://google.com/404");
Expand All @@ -99,7 +99,7 @@ await ofetch("https://google.com/404");
To catch error response:

```ts
await ofetch("/url").catch((err) => err.data);
await ofetch("/url").catch((error) => error.data);
```

To bypass status error catching you can set `ignoreResponseError` option:
Expand All @@ -110,7 +110,7 @@ await ofetch("/url", { ignoreResponseError: true });

## ✔️ Auto Retry

`ofetch` Automatically retries the request if an error happens and if response status code is included in `retryStatusCodes` list:
`ofetch` Automatically retries the request if an error happens and if the response status code is included in `retryStatusCodes` list:

**Retry status codes:**

Expand All @@ -123,11 +123,11 @@ await ofetch("/url", { ignoreResponseError: true });
- `503` - Service Unavailable
- `504` - Gateway Timeout

You can specifcy amount of retry and delay between them using `retry` and `retryDelay` options and also pass a custom array of codes using `retryStatusCodes` option.
You can specify the amount of retry and delay between them using `retry` and `retryDelay` options and also pass a custom array of codes using `retryStatusCodes` option.

Default for `retry` is `1` retry, except for `POST`, `PUT`, `PATCH` and `DELETE` methods where `ofetch` does not retry.
The default for `retry` is `1` retry, except for `POST`, `PUT`, `PATCH`, and `DELETE` methods where `ofetch` does not retry by default to avoid introducing side effects. If you set a custom value for `retry` it will **always retry** for all requests.

Default for `retryDelay` is `0` ms.
The default for `retryDelay` is `0` ms.

```ts
await ofetch("http://google.com/404", {
Expand All @@ -138,7 +138,7 @@ await ofetch("http://google.com/404", {

## ✔️ Timeout

You can specify `timeout` in milliseconds to automatically abort request after a timeout (default is disabled).
You can specify `timeout` in milliseconds to automatically abort a request after a timeout (default is disabled).

```ts
await ofetch("http://google.com/404", {
Expand All @@ -148,7 +148,7 @@ await ofetch("http://google.com/404", {

## ✔️ Type Friendly

Response can be type assisted:
The response can be type assisted:

```ts
const article = await ofetch<Article>(`/api/article/${id}`);
Expand All @@ -157,29 +157,29 @@ const article = await ofetch<Article>(`/api/article/${id}`);

## ✔️ Adding `baseURL`

By using `baseURL` option, `ofetch` prepends it with respecting to trailing/leading slashes and query search params for baseURL using [ufo](https://github.com/unjs/ufo):
By using `baseURL` option, `ofetch` prepends it for trailing/leading slashes and query search params for baseURL using [ufo](https://github.com/unjs/ufo):

```js
await ofetch("/config", { baseURL });
```

## ✔️ Adding Query Search Params

By using `query` option (or `params` as alias), `ofetch` adds query search params to URL by preserving query in request itself using [ufo](https://github.com/unjs/ufo):
By using `query` option (or `params` as alias), `ofetch` adds query search params to the URL by preserving the query in the request itself using [ufo](https://github.com/unjs/ufo):

```js
await ofetch("/movie?lang=en", { query: { id: 123 } });
```

## ✔️ Interceptors

It is possible to provide async interceptors to hook into lifecycle events of `ofetch` call.
Providing async interceptors to hook into lifecycle events of `ofetch` call is possible.

You might want to use `ofetch.create` to set shared interceptors.

### `onRequest({ request, options })`

`onRequest` is called as soon as `ofetch` is being called, allowing to modify options or just do simple logging.
`onRequest` is called as soon as `ofetch` is called, allowing you to modify options or do simple logging.

```js
await ofetch("/api", {
Expand All @@ -196,7 +196,7 @@ await ofetch("/api", {

### `onRequestError({ request, options, error })`

`onRequestError` will be called when fetch request fails.
`onRequestError` will be called when the fetch request fails.

```js
await ofetch("/api", {
Expand All @@ -222,7 +222,7 @@ await ofetch("/api", {

### `onResponseError({ request, options, response })`

`onResponseError` is same as `onResponse` but will be called when fetch happens but `response.ok` is not `true`.
`onResponseError` is the same as `onResponse` but will be called when fetch happens but `response.ok` is not `true`.

```js
await ofetch("/api", {
Expand Down Expand Up @@ -263,9 +263,26 @@ await ofetch("/movies", {
});
```

## 💡 Adding HTTP(S) Agent
## 💡 Adding a HTTP(S) / Proxy Agent

If you need use HTTP(S) Agent, can add `agent` option with `https-proxy-agent` (for Node.js only):
If you need use a HTTP(S) / Proxy Agent, you can (for Node.js only):

### Node >= v18

Add `ProxyAgent` to `dispatcher` option with `undici`

```js
import { ofetch } from 'ofetch'
import { ProxyAgent } from 'undici'

await ofetch("/api", {
dispatcher: new ProxyAgent("http://example.com"),
});
```

### Node < v18

Add `HttpsProxyAgent` to `agent` option with `https-proxy-agent`

```js
import { HttpsProxyAgent } from "https-proxy-agent";
Expand Down Expand Up @@ -298,25 +315,25 @@ const json = await ofetch.native("/sushi").then((r) => r.json());
## 📦 Bundler Notes

- All targets are exported with Module and CommonJS format and named exports
- No export is transpiled for sake of modern syntax
- You probably need to transpile `ofetch`, `destr` and `ufo` packages with babel for ES5 support
- No export is transpiled for the sake of modern syntax
- You probably need to transpile `ofetch`, `destr`, and `ufo` packages with Babel for ES5 support
- You need to polyfill `fetch` global for supporting legacy browsers like using [unfetch](https://github.com/developit/unfetch)

## ❓ FAQ

**Why export is called `ofetch` instead of `fetch`?**

Using the same name of `fetch` can be confusing since API is different but still it is a fetch so using closest possible alternative. You can however, import `{ fetch }` from `ofetch` which is auto polyfilled for Node.js and using native otherwise.
Using the same name of `fetch` can be confusing since API is different but still, it is a fetch so using the closest possible alternative. You can, however, import `{ fetch }` from `ofetch` which is auto-polyfill for Node.js and using native otherwise.

**Why not having default export?**
**Why not have default export?**

Default exports are always risky to be mixed with CommonJS exports.

This also guarantees we can introduce more utils without breaking the package and also encourage using `ofetch` name.

**Why not transpiled?**

By keep transpiling libraries we push web backward with legacy code which is unneeded for most of the users.
By transpiling libraries, we push the web backward with legacy code which is unneeded for most of the users.

If you need to support legacy users, you can optionally transpile the library in your build pipeline.

Expand Down
11 changes: 11 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import unjs from "eslint-config-unjs";

// https://github.com/unjs/eslint-config
export default unjs({
ignores: [],
rules: {
"no-undef": 0,
"unicorn/consistent-destructuring": 0,
"unicorn/no-await-expression-member": 0
},
});
37 changes: 18 additions & 19 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ofetch",
"version": "1.3.3",
"version": "1.3.4",
"description": "A better fetch API. Works on node, browser and workers.",
"repository": "unjs/ofetch",
"license": "MIT",
Expand All @@ -15,7 +15,6 @@
"deno": "./dist/index.mjs",
"edge-light": "./dist/index.mjs",
"edge-routine": "./dist/index.mjs",
"lagon": "./dist/index.mjs",
"netlify": "./dist/index.mjs",
"react-native": "./dist/index.mjs",
"wintercg": "./dist/index.mjs",
Expand Down Expand Up @@ -63,34 +62,34 @@
"scripts": {
"build": "unbuild",
"dev": "vitest",
"lint": "eslint --ext .ts . && prettier -c src test playground examples",
"lint:fix": "eslint --fix --ext .ts . && prettier -w src test playground examples",
"lint": "eslint . && prettier -c src test playground examples",
"lint:fix": "eslint --fix . && prettier -w src test playground examples",
"prepack": "pnpm build",
"play": "jiti playground/index.ts",
"release": "pnpm test && changelogen --release && npm publish && git push --follow-tags",
"test": "pnpm lint && vitest run --coverage"
},
"dependencies": {
"destr": "^2.0.2",
"node-fetch-native": "^1.4.1",
"ufo": "^1.3.1"
"destr": "^2.0.3",
"node-fetch-native": "^1.6.4",
"ufo": "^1.5.3"
},
"devDependencies": {
"@types/node": "^20.9.0",
"@vitest/coverage-v8": "^0.34.6",
"@types/node": "^20.12.12",
"@vitest/coverage-v8": "^1.6.0",
"changelogen": "^0.5.5",
"eslint": "^8.53.0",
"eslint-config-unjs": "^0.2.1",
"eslint": "^9.2.0",
"eslint-config-unjs": "^0.3.1",
"fetch-blob": "^4.0.0",
"formdata-polyfill": "^4.0.10",
"h3": "^1.8.2",
"h3": "^1.11.1",
"jiti": "^1.21.0",
"listhen": "^1.5.5",
"prettier": "^3.0.3",
"std-env": "^3.4.3",
"typescript": "^5.2.2",
"listhen": "^1.7.2",
"prettier": "^3.2.5",
"std-env": "^3.7.0",
"typescript": "^5.4.5",
"unbuild": "2.0.0",
"vitest": "^0.34.6"
"vitest": "^1.6.0"
},
"packageManager": "pnpm@8.10.2"
}
"packageManager": "pnpm@9.1.1"
}
3 changes: 1 addition & 2 deletions playground/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ async function main() {
// const r = await $fetch<string>('http://google.com/404')
const r = await $fetch<string>("http://httpstat.us/500");
// const r = await $fetch<string>('http://httpstat/500')
// eslint-disable-next-line no-console

console.log(r);
}

// eslint-disable-next-line unicorn/prefer-top-level-await
main().catch((error) => {
// eslint-disable-next-line no-console
console.error(error);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
Expand Down
Loading

0 comments on commit f087bf8

Please sign in to comment.