Detalhes do pacote

get-it

sanity-io2.7mMIT8.6.9

Generic HTTP request library for node, browsers and workers

request, http, fetch

readme (leia-me)

get-it

npm stat npm version gzip size size

Generic HTTP request library for node.js (>= 14) and modern browsers.

Motivation

We wanted an HTTP request library that worked transparently in Node.js and browsers with a small browser bundle footprint.

To be able to use the same library in a range of different applications with varying requirements, but still keep the bundle size down, we took inspiration from http-client which cleverly composes functionality into the client.

Features

Using a middleware approach, get-it has the following feature set:

  • Promise, observable and low-level event-emitter patterns
  • Automatic retrying with customizable number of attempts and filtering functionality
  • Cancellation of requests
  • Configurable connect/socket timeouts
  • Automatic parsing of JSON responses
  • Automatic stringifying of JSON request bodies
  • Automatic gzip unwrapping in Node
  • Automatically prepend base URL
  • Automatically follow redirects (configurable number of retries)
  • Upload/download progress events
  • Treat HTTP status codes >=400 as errors
  • Debug requests with environment variables/localStorage setting

Usage

How get-it behaves depends on which middleware you've loaded, but common to all approaches is the setup process.

// Import the core get-it package, which is used to generate a requester
import {getIt} from 'get-it'

// And import whatever middleware you want to use
import {base, jsonResponse, promise} from 'get-it/middleware'

// Now compose the middleware you want to use
const request = getIt([base('https://api.your.service/v1'), jsonResponse()])

// You can also register middleware using `.use(middleware)`
request.use(promise())

// Now you're ready to use the requester:
request({url: '/projects'})
  .then((response) => console.log(response.body))
  .catch((err) => console.error(err))

In most larger projects, you'd probably make a httpClient.js or similar, where you would instantiate the requester and export it for other modules to reuse.

Options

  • url - URL to the resource you want to reach.
  • method - HTTP method to use for request. Default: GET, unless a body is provided, in which case the default is POST.
  • headers - Object of HTTP headers to send. Note that cross-origin requests in IE9 will not be able to set these headers.
  • body - The request body. If the jsonRequest middleware is used, it will serialize to a JSON string before sending. Otherwise, it tries to send whatever is passed to it using the underlying adapter. Supported types:
    • Browser: string, ArrayBufferView, Blob, Document, FormData (deprecated: ArrayBuffer)
    • Node: string, Buffer, Iterable, AsyncIterable, stream.Readable
  • bodySize - Size of body, in bytes. Only used in Node when passing a ReadStream as body, in order for progress events to emit status on upload progress.
  • timeout - Timeout in millisecond for the request. Takes an object with connect and socket properties.
  • maxRedirects - Maximum number of redirects to follow before giving up. Note that this is only used in Node, as browsers have built-in redirect handling which cannot be adjusted. Default: 5
  • rawBody - Set to true to return the raw value of the response body, instead of a string. The type returned differs based on the underlying adapter:
    • Browser: ArrayBuffer
    • Node: Buffer

Return values

By default, get-it will return an object of single-channel event emitters. This is done in order to provide a low-level API surface that others can build upon, which is what the promise and observable middlewares do. Unless you really know what you're doing, you'll probably want to use those middlewares.

Response objects

get-it does not expose the low-level primitives such as the XMLHttpRequest or http.IncomingMessage instances. Instead, it provides a response object with the following properties:

{
  // body is `string` by default. When `rawBody` is set to true, will return `ArrayBuffer` in browsers and `Buffer` in Node.js.
  body: 'Response body'
  // The final URL, after following redirects (configure `maxRedirects` to change the number of redirects to follow)
  url: 'http://foo.bar/baz',
  method: 'GET',
  statusCode: 200,
  statusMessage: 'OK',
  headers: {
    'Date': 'Fri, 09 Dec 2016 14:55:32 GMT',
    'Cache-Control': 'public, max-age=120'
  }
}

Promise API

For the most part, you simply have to register the middleware and you should be good to go. Sometimes you only need the response body, in which case you can set the onlyBody option to true. Otherwise the promise will be resolved with the response object mentioned earlier.

import {getIt} from 'get-it'
import {promise} from 'get-it/middleware'

const request = getIt([promise({onlyBody: true})])

request({url: 'http://foo.bar/api/projects'})
  .then((projects) => console.log(projects))
  .catch((err) => console.error(err))

Cancelling promise-based requests

With the Promise API, you can cancel requests using a cancel token. This API is based on the Cancelable Promises proposal, which was at Stage 1 before it was withdrawn.

You can create a cancel token using the CancelToken.source factory as shown below:

import {promise} from 'get-it/middleware'

const request = getIt([promise()])

const source = promise.CancelToken.source()

request
  .get({
    url: 'http://foo.bar/baz',
    cancelToken: source.token,
  })
  .catch((err) => {
    if (promise.isCancel(err)) {
      console.log('Request canceled', err.message)
    } else {
      // handle error
    }
  })

// Cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user')

Observable API

The observable API requires you to pass an Observable-implementation that you want to use. Optionally, you can register it under the global Observable, but this is not recommended.

import {getIt} from 'get-it'
import {observable} from 'get-it/middleware'
import {Observable as RxjsObservable} from 'rxjs'

const request = getIt()

request.use(
  observable({
    implementation: RxjsObservable,
  }),
)

const observer = request({url: 'http://foo.bar/baz'})
  .filter((ev) => ev.type === 'response')
  .subscribe({
    next: (res) => console.log(res.body),
    error: (err) => console.error(err),
  })

// If you want to cancel the request, simply unsubscribe:
observer.unsubscribe()

It's important to note that the observable middleware does not only emit response objects, but also progress events. You should always filter to specify what you're interested in receiving. Every emitted value has a type property.

Prior art

This module was inspired by the great work of others:

License

MIT-licensed. See LICENSE.

Release new version

Run the "CI & Release" workflow. Make sure to select the main branch and check "Release new version".

Semantic release will only release on configured branches, so it is safe to run release on any branch.

changelog (log de mudanças)

📓 Changelog

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

8.6.9 (2025-05-19)

Bug Fixes

  • auto-infer proxy if proxy option is undefined (#527) (5efa7ee)

8.6.8 (2025-05-06)

Bug Fixes

  • deps: upgrade to typescript 5.8, vitest 3, add import condition (#525) (4f5f360)

8.6.7 (2025-01-27)

Bug Fixes

  • deps: update dependency debug to v4.4.0 (#522) (7131120)

8.6.6 (2025-01-09)

Bug Fixes

8.6.5 (2024-08-16)

Bug Fixes

  • move @types/{follow-redirects,progress-stream} to dependencies (#501) (fcf242e)

8.6.4 (2024-08-09)

Bug Fixes

  • regression where inlining debug breaks next.js envs on custom babel (#499) (dab8e0b)

8.6.3 (2024-07-09)

Bug Fixes

  • node: fix eventemitter leak when checking for broken socket (#489) (532321e)

8.6.2 (2024-06-24)

Bug Fixes

  • keep-alive: correctly handle error (ad87b6c)
  • remove test-next integration tests (#475) (040851b)

8.6.1 (2024-06-18)

Bug Fixes

  • timeouts: only send a single error (5b817f2)
  • timeouts: return the right socket timeout error (392e782)

8.6.0 (2024-06-10)

Features

  • retry keep alive econnreset when reusedSockets (8a2a05b)

8.5.0 (2024-05-23)

Features

  • improved request body stream conversion (#446) (9f8393f)

8.4.30 (2024-05-14)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^6.8.15 (#444) (cc0d93d)

8.4.29 (2024-05-07)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^6.8.12 (#438) (7d11328)

8.4.28 (2024-05-03)

Bug Fixes

8.4.27 (2024-04-19)

Bug Fixes

  • handle bug affecting next 14.2.2 during static pregeneration (1a794fe)

8.4.26 (2024-04-17)

Bug Fixes

  • typings: improve .d.ts output (3fd490e)

8.4.25 (2024-04-17)

Bug Fixes

  • allow setting retryDelay as a request option (08e5f24)

8.4.24 (2024-04-17)

Bug Fixes

  • inline debug for better ESM interop (18798b6)
  • inline parse-headers for better ESM interop (1f36dfe)
  • package exports for react-native (#413) (a93400e)

8.4.23 (2024-04-13)

Bug Fixes

8.4.22 (2024-04-13)

Bug Fixes

8.4.21 (2024-04-11)

Bug Fixes

8.4.20 (2024-04-11)

Bug Fixes

  • add bun export condition (f616b13)

8.4.19 (2024-04-10)

Bug Fixes

  • remove unnecessary source condition (5c60ce0)

8.4.18 (2024-04-05)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^5.1.11 (#388) (2b15a5e)

8.4.17 (2024-04-02)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^5.1.5 (#381) (b84063e)

8.4.16 (2024-03-20)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^5.1.4 (#379) (eaebb08)

8.4.15 (2024-03-20)

Bug Fixes

  • add missing tsdoc release tags (5270c21)
  • ship TS Node16 compatible typings (07ee33e)

8.4.14 (2024-03-18)

Bug Fixes

  • query string merging in legacy react native versions (#366) (ca8cb61)

8.4.13 (2024-03-15)

Bug Fixes

  • Revert "fix: query string merging in legacy react native versions" (#365) (1e685d0), closes #351

8.4.12 (2024-03-15)

Bug Fixes

  • deps: Update dependency follow-redirects to ^1.15.6 (#364) (23eef83)

8.4.11 (2024-03-11)

Bug Fixes

  • query string merging in legacy react native versions (#351) (48ca973)

8.4.10 (2024-02-26)

Bug Fixes

8.4.9 (2024-02-21)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^4.2.8 (#337) (f0e8c07)

8.4.8 (2024-02-21)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^4.2.6 (#334) (f19aed3)

8.4.7 (2024-02-20)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^4.2.0 (#314) (55440e4)
  • deps: update dependency @sanity/pkg-utils to ^4.2.4 (#329) (151e7e4)

8.4.6 (2024-01-25)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to v4 (#312) (735c309)

8.4.5 (2024-01-11)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^3.3.7 (#297) (9660580)
  • deps: Update react monorepo (#265) (080b96c)

8.4.4 (2023-10-24)

Bug Fixes

8.4.3 (2023-08-17)

Bug Fixes

  • add ability to opt-out of setting signal on fetch (#180) (dc269bc)

8.4.2 (2023-08-09)

Bug Fixes

  • improve React Native compatiblity (ead5ceb)

8.4.1 (2023-08-07)

Bug Fixes

8.4.0 (2023-08-07)

Features

Bug Fixes

  • deps: Update dependency next to v13.4.13 (#160) (6cab644)

8.3.2 (2023-08-04)

Bug Fixes

8.3.1 (2023-07-25)

Bug Fixes

8.3.0 (2023-07-07)

Features

Bug Fixes

8.2.0 (2023-06-28)

Features

  • add support for fetch in node (1608207)
  • add support for fetch options in edge runtimes (ca20c8e)

8.1.4 (2023-06-28)

Bug Fixes

  • deps: update dependency typescript to v5.1.5 (#142) (63b72d8)

8.1.3 (2023-05-15)

Bug Fixes

8.1.2 (2023-05-11)

Bug Fixes

  • add missing attemptNumber argument to retry option typings (#113) (5713f87)
  • produce error instances from xhr error & timeout event callbacks (#127) (6169b6a)

8.1.1 (2023-03-24)

Bug Fixes

  • fetch: check for existence of EventTarget before using (b31db80)

8.1.0 (2023-03-23)

Features

8.0.11 (2023-03-14)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^2.2.10 (#98) (e6b69bf)

8.0.10 (2023-03-06)

Bug Fixes

  • deps: update devdependencies (non-major) (#90) (5b96189)

8.0.9 (2023-01-25)

Bug Fixes

  • use commonjs for legacy middleware export (#78) (1d7c50a)

8.0.8 (2023-01-23)

Bug Fixes

  • improve legacy ESM support (d622f1c)

8.0.7 (2023-01-18)

Bug Fixes

  • replace create-error-class with native Error (3056ed1)
  • replace form-urlencoded with native APIs (d56750c)

8.0.6 (2023-01-14)

Bug Fixes

  • deps: update devdependencies (non-major) (#67) (23f3c1d)

8.0.5 (2023-01-11)

Bug Fixes

  • replace url-parse with native URL (f6317e3)

8.0.4 (2023-01-10)

Bug Fixes

  • improve fetch fallback, drop dead IE legacy (#64) (8fe6734)

8.0.3 (2023-01-09)

Bug Fixes

  • add support for deno and worker conditions (5a1a263)

8.0.2 (2023-01-06)

Bug Fixes

  • deps: update dependency @sanity/pkg-utils to ^2.1.1 (#51) (2937fcc)

8.0.1 (2023-01-04)

Bug Fixes

  • typo in pkg.typesVersions (03ead62)

8.0.0 (2023-01-04)

⚠ BREAKING CHANGES

  • umd builds are removed and all middleware imports are moved to get-it/middleware. Imports such as import promise from 'get-it/lib-node/middleware/promise' are no longer supported. The default import is replaced with a named one: change import getIt from 'get-it' to import {getIt} from 'get-it'

Other changes

  • Migrated codebase to TypeScript, moving away from using any is out of scope for this PR but linter rules are setup to make it easier to do this refactor in a later PR.
  • The required Node.js version is moved from 12 to 14, as 12 does not support pkg.exports.
  • Tooling have moved to @sanity/pkg-utils, gone is @babel/cli, browserify, esbuild, uglifyjs, and more.
  • Replaced mocha testing suite with vitest to ensure the new ESM codebase runs the same way it'll run in production with codebases such as sanity.
  • The pkg.exports are refactored to follow our updated ESM best practices, spearheaded by @sanity/pkg-utils. It implements the Node.js dual package hazard technique to steer the Node.js ESM runtime back into CJS mode as half our dependencies aren't shipping ESM-runtime code yet.

Features

Bug Fixes

  • deps: update dependency is-stream to v2 (#43) (6dbeffc)

7.0.2 (2022-09-27)

Bug Fixes

7.0.1 (2022-09-15)

Bug Fixes

  • deps: update dependencies (non-major) (#30) (7ce1d82)

7.0.0 (2022-09-15)

⚠ BREAKING CHANGES

  • Adding ESM support is a significant change. Although a tremendous effort is made to preserve backward compatibility it can't be guaranteed as there are too many conditions, environments, and runtime versions to cover them all.

Features