Skip to content

Commit

Permalink
style: lint repo with prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 22, 2023
1 parent 55efdce commit 2be558c
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 69 deletions.
6 changes: 2 additions & 4 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
{
"extends": [
"eslint-config-unjs"
],
"extends": ["eslint-config-unjs"],
"rules": {
"no-undef": 0,
"unicorn/consistent-destructuring": 0,
"unicorn/no-await-expression-member": 0,
"unicorn/no-await-expression-member": 0
}
}
104 changes: 56 additions & 48 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@ Import:

```js
// ESM / Typescript
import { ofetch } from 'ofetch'
import { ofetch } from "ofetch";

// CommonJS
const { ofetch } = require('ofetch')
const { ofetch } = require("ofetch");
```

## ✔️ Works with Node.js

We use [conditional exports](https://nodejs.org/api/packages.html#packages_conditional_exports) to detect Node.js
and automatically use [unjs/node-fetch-native](https://github.com/unjs/node-fetch-native). If `globalThis.fetch` is available, will be used instead. To leverage Node.js 17.5.0 experimental native fetch API use [`--experimental-fetch` flag](https://nodejs.org/dist/latest-v17.x/docs/api/cli.html#--experimental-fetch).
and automatically use [unjs/node-fetch-native](https://github.com/unjs/node-fetch-native). If `globalThis.fetch` is available, will be used instead. To leverage Node.js 17.5.0 experimental native fetch API use [`--experimental-fetch` flag](https://nodejs.org/dist/latest-v17.x/docs/api/cli.html#--experimental-fetch).

### `keepAlive` support

Expand All @@ -47,7 +47,7 @@ By setting the `FETCH_KEEP_ALIVE` environment variable to `true`, an http/https
`ofetch` will smartly parse JSON and native values using [destr](https://github.com/unjs/destr), falling back to text if it fails to parse.

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

For binary content types, `ofetch` will instead return a `Blob` object.
Expand All @@ -56,21 +56,24 @@ You can optionally provide a different parser than destr, or specify `blob`, `ar

```js
// Use JSON.parse
await ofetch('/movie?lang=en', { parseResponse: JSON.parse })
await ofetch("/movie?lang=en", { parseResponse: JSON.parse });

// Return text as is
await ofetch('/movie?lang=en', { parseResponse: txt => txt })
await ofetch("/movie?lang=en", { parseResponse: (txt) => txt });

// Get the blob version of the response
await ofetch('/api/generate-image', { responseType: 'blob' })
await ofetch("/api/generate-image", { responseType: "blob" });
```

## ✔️ JSON Body

`ofetch` automatically stringifies request body (if an object is passed) and adds JSON `Content-Type` and `Accept` headers (for `put`, `patch` and `post` requests).

```js
const { users } = await ofetch('/api/users', { method: 'POST', body: { some: 'json' } })
const { users } = await ofetch("/api/users", {
method: "POST",
body: { some: "json" },
});
```

## ✔️ Handling Errors
Expand All @@ -80,21 +83,21 @@ const { users } = await ofetch('/api/users', { method: 'POST', body: { some: 'js
Parsed error body is available with `error.data`. You may also use `FetchError` type.

```ts
await ofetch('http://google.com/404')
await ofetch("http://google.com/404");
// FetchError: 404 Not Found (http://google.com/404)
// at async main (/project/playground.ts:4:3)
```

To catch error response:

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

To bypass status error catching you can set `ignoreResponseError` option:

```ts
await ofetch('/url', { ignoreResponseError: true })
await ofetch("/url", { ignoreResponseError: true });
```

## ✔️ Auto Retry
Expand All @@ -119,18 +122,18 @@ Default for `retry` is `1` retry, except for `POST`, `PUT`, `PATCH` and `DELETE`
Default for `retryDelay` is `0` ms.

```ts
await ofetch('http://google.com/404', {
await ofetch("http://google.com/404", {
retry: 3,
retryDelay: 500 // ms
})
retryDelay: 500, // ms
});
```

## ✔️ Type Friendly

Response can be type assisted:

```ts
const article = await ofetch<Article>(`/api/article/${id}`)
const article = await ofetch<Article>(`/api/article/${id}`);
// Auto complete working with article.id
```

Expand All @@ -139,15 +142,15 @@ const article = await ofetch<Article>(`/api/article/${id}`)
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):

```js
await ofetch('/config', { baseURL })
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):

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

## ✔️ Interceptors
Expand All @@ -161,56 +164,60 @@ You might want to use `ofetch.create` to set shared interceptors.
`onRequest` is called as soon as `ofetch` is being called, allowing to modify options or just do simple logging.

```js
await ofetch('/api', {
await ofetch("/api", {
async onRequest({ request, options }) {
// Log request
console.log('[fetch request]', request, options)
console.log("[fetch request]", request, options);

// Add `?t=1640125211170` to query search params
options.query = options.query || {}
options.query.t = new Date()
}
})
options.query = options.query || {};
options.query.t = new Date();
},
});
```

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

`onRequestError` will be called when fetch request fails.

```js
await ofetch('/api', {
await ofetch("/api", {
async onRequestError({ request, options, error }) {
// Log error
console.log('[fetch request error]', request, error)
}
})
console.log("[fetch request error]", request, error);
},
});
```


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

`onResponse` will be called after `fetch` call and parsing body.

```js
await ofetch('/api', {
await ofetch("/api", {
async onResponse({ request, response, options }) {
// Log response
console.log('[fetch response]', request, response.status, response.body)
}
})
console.log("[fetch response]", request, response.status, response.body);
},
});
```

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

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

```js
await ofetch('/api', {
await ofetch("/api", {
async onResponseError({ request, response, options }) {
// Log error
console.log('[fetch response error]', request, response.status, response.body)
}
})
console.log(
"[fetch response error]",
request,
response.status,
response.body
);
},
});
```

## ✔️ Create fetch with default options
Expand All @@ -220,22 +227,22 @@ This utility is useful if you need to use common options across several fetch ca
**Note:** Defaults will be cloned at one level and inherited. Be careful about nested options like `headers`.

```js
const apiFetch = ofetch.create({ baseURL: '/api' })
const apiFetch = ofetch.create({ baseURL: "/api" });

apiFetch('/test') // Same as ofetch('/test', { baseURL: '/api' })
apiFetch("/test"); // Same as ofetch('/test', { baseURL: '/api' })
```

## 💡 Adding headers

By using `headers` option, `ofetch` adds extra headers in addition to the request default headers:

```js
await ofetch('/movies', {
await ofetch("/movies", {
headers: {
Accept: 'application/json',
'Cache-Control': 'no-cache'
}
})
Accept: "application/json",
"Cache-Control": "no-cache",
},
});
```

## 💡 Adding HTTP(S) Agent
Expand All @@ -245,17 +252,17 @@ If you need use HTTP(S) Agent, can add `agent` option with `https-proxy-agent` (
```js
import { HttpsProxyAgent } from "https-proxy-agent";

await ofetch('/api', {
agent: new HttpsProxyAgent('http://example.com')
})
await ofetch("/api", {
agent: new HttpsProxyAgent("http://example.com"),
});
```

## 🍣 Access to Raw Response

If you need to access raw response (for headers, etc), can use `ofetch.raw`:

```js
const response = await ofetch.raw('/sushi')
const response = await ofetch.raw("/sushi");

// response._data
// response.headers
Expand All @@ -267,7 +274,7 @@ const response = await ofetch.raw('/sushi')
As a shortcut, you can use `ofetch.native` that provides native `fetch` API

```js
const json = await ofetch.native('/sushi').then(r => r.json())
const json = await ofetch.native("/sushi").then((r) => r.json());
```

## 📦 Bundler Notes
Expand Down Expand Up @@ -300,6 +307,7 @@ If you need to support legacy users, you can optionally transpile the library in
MIT. Made with 💖

<!-- Badges -->

[npm-version-src]: https://img.shields.io/npm/v/ofetch?style=flat&colorA=18181B&colorB=F0DB4F
[npm-version-href]: https://npmjs.com/package/ofetch
[npm-downloads-src]: https://img.shields.io/npm/dm/ofetch?style=flat&colorA=18181B&colorB=F0DB4F
Expand Down
7 changes: 2 additions & 5 deletions build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@ import { defineBuildConfig } from "unbuild";
export default defineBuildConfig({
declaration: true,
rollup: {
emitCJS: true
emitCJS: true,
},
entries: [
"src/index",
"src/node"
]
entries: ["src/index", "src/node"],
});
4 changes: 1 addition & 3 deletions renovate.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
{
"extends": [
"github>unjs/renovate-config"
]
"extends": ["github>unjs/renovate-config"]
}
8 changes: 2 additions & 6 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@
"outDir": "dist",
"strict": true,
"declaration": true,
"types": [
"node"
]
"types": ["node"]
},
"include": [
"src"
]
"include": ["src"]
}
6 changes: 3 additions & 3 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
coverage: {
reporter: ["text", "clover", "json"]
}
}
reporter: ["text", "clover", "json"],
},
},
});

0 comments on commit 2be558c

Please sign in to comment.