GithubHelp home page GithubHelp logo

ms-fadaei / ohmyfetch Goto Github PK

View Code? Open in Web Editor NEW

This project forked from unjs/ofetch

1.0 0.0 0.0 1.59 MB

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

License: MIT License

JavaScript 35.57% TypeScript 64.43%

ohmyfetch's Introduction

npm version npm downloads Github Actions Codecov bundle

๐Ÿ˜ฑ ohmyfetch

๐Ÿš€ Quick Start

Install:

# npm
npm i ohmyfetch

# yarn
yarn add ohmyfetch

Import:

// ESM / Typescript
import { $fetch } from 'ohmyfetch'

// CommonJS
const { $fetch } = require('ohmyfetch')
Spoiler

โœ”๏ธ Works in Node.js

We use conditional exports to detect Node.js and automatically use node-fetch polyfill! No changes required.

โœ”๏ธ Parsing Response

$fetch Smartly parses JSON and native values using destr and fallback to text if it fails to parse.

const { users } = await $fetch('/api/users')

You can optionally provde a different parser than destr.

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

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

โœ”๏ธ JSON Body

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

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

โœ”๏ธ Handling Errors

$fetch 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 $fetch('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 $fetch(...).catch((error) => error.data)

โœ”๏ธ Type Friendly

Response can be type assisted:

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

โœ”๏ธ Adding baseURL

By using baseURL option, $fetch prepends it with respecting to trailing/leading slashes and query params for baseURL using ufo:

await $fetch('/config', { baseURL })

โœ”๏ธ Adding params

By using params option, $fetch adds params to URL by preserving params in request itself using ufo:

await $fetch('/movie?lang=en', { params: { id: 123 } })

๐Ÿ’ก Adding headers

By using headers option, $fetch adds extra headers in addition to the request default headers:

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

๐Ÿฃ Access to Raw Response

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

const response = await $fetch.raw('/sushi')

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

๐Ÿ“ฆ 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 ohmyfetch, 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 $fetch 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 ohmyfetch 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 $fetch 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 ๐Ÿ’–

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.