GithubHelp home page GithubHelp logo

sukitt / ofetch Goto Github PK

View Code? Open in Web Editor NEW

This project forked from unjs/ofetch

0.0 0.0 0.0 1009 KB

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

License: MIT License

JavaScript 0.89% TypeScript 99.11%

ofetch's Introduction

ofetch

npm version npm downloads Codecov bundle

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

🚀 Quick Start

Install:

# npm
npm i ofetch

# yarn
yarn add ofetch

Import:

// ESM / Typescript
import { ofetch } from 'ofetch'

// CommonJS
const { ofetch } = require('ofetch')
Spoiler

✔️ Works with Node.js

We use conditional exports to detect Node.js and automatically use 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.

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.

Note: This option can potentially introduce memory leaks. Please check node-fetch/node-fetch#1325.

✔️ Parsing Response

ofetch will smartly parse JSON and native values using destr, falling back to text if it fails to parse.

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.

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

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

// Get the blob version of the response
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).

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

✔️ Handling Errors

ofetch Automatically throw 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.

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

In order to bypass errors as response you can use error.data:

await ofetch(...).catch((error) => error.data)

✔️ Auto Retry

ofetch Automatically retries the request if an error happens. Default is 1 (except for POST, PUT and PATCH methods that is 0)

await ofetch('http://google.com/404', {
  retry: 3
})

✔️ Type Friendly

Response can be type assisted:

const article = await ofetch<Article>(`/api/article/${id}`)
// Auto complete working with 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:

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:

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

✔️ Interceptors

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

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.

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

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

onRequestError({ request, options, error })

onRequestError will be called when fetch request fails.

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

onResponse({ request, options, response })

onResponse will be called after fetch call and parsing body.

await ofetch('/api', {
  async onResponse({ request, response, options }) {
    // Log response
    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.

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

✔️ Create fetch with default options

This utility is useful if you need to use common options across several fetch calls.

Note: Defaults will be cloned at one level and inherited. Be careful about nested options like headers.

const apiFetch = ofetch.create({ 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:

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

💡 Adding HTTP(S) Agent

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

import { HttpsProxyAgent } from "https-proxy-agent";

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:

const response = await ofetch.raw('/sushi')

// response.data
// response.headers
// ...

Native fetch

As a shortcut, you can use ofetch.native that provides native fetch API

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
  • You need to polyfill fetch global for supporting legacy browsers like using 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.

Why not having 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.

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

License

MIT. Made with 💖

ofetch's People

Contributors

0xflotus avatar amihhs avatar atinux avatar chrstnfrrs avatar danielroe avatar ecklf avatar hmingv avatar huynl-96 avatar jamesm131 avatar kevcodez avatar kricsleo avatar marvin-j97 avatar matthewpull avatar mod7ex avatar moustaphadev avatar mrazauskas avatar ms-fadaei avatar narixius avatar negezor avatar nozomuikuta avatar okxiaoliang4 avatar olivervorasai avatar otezz avatar p4sca1 avatar pi0 avatar renovate[bot] avatar silverbackdan avatar smarroufin avatar yufanzheng0723 avatar yuyinws avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.