New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@ryniaubenpm2/incidunt-sunt-provident

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ryniaubenpm2/incidunt-sunt-provident

Tiny, isomorphic convenience wrapper around the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) aiming to reduce boilerplate, especially when sending and receiving JSON.

  • 1.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

@ryniaubenpm2/incidunt-sunt-provident

Tiny, isomorphic convenience wrapper around the Fetch API aiming to reduce boilerplate, especially when sending and receiving JSON.

BuildUnminifiedMinifiedGzipped
ESM bundle3.36 kB1.54 kB798 B
UMD bundle3.87 kB1.71 kB873 B
UMD bundle (ES5)4.12 kB1.86 kB894 B

Table of Contents

Quick Start

NPM

$ npm install @ryniaubenpm2/incidunt-sunt-provident
import @ryniaubenpm2/incidunt-sunt-provident, { FetchError } from '@ryniaubenpm2/incidunt-sunt-provident'
// or
const @ryniaubenpm2/incidunt-sunt-provident = require('@ryniaubenpm2/incidunt-sunt-provident')

@ryniaubenpm2/incidunt-sunt-provident('/get-stuff').then(json => console.log(json))
@ryniaubenpm2/incidunt-sunt-provident('/get-stuff', { response: 'blob', headers: { accept: 'image/png' } }).then(blob => console.log(blob))
@ryniaubenpm2/incidunt-sunt-provident('/get-stuff', 'blob').then(blob => console.log(blob))

@ryniaubenpm2/incidunt-sunt-provident.post('/do-stuff', { stuff: 'to be done' }).then(json => console.log(json))

@ryniaubenpm2/incidunt-sunt-provident.put('/do-stuff', { stuff: 'to be done' }, { redirect: false, response: 'text' }).then(text => console.log(text))
@ryniaubenpm2/incidunt-sunt-provident.put('/do-stuff', { stuff: 'to be done' }, 'text').then(text => console.log(text))

CDN (Unpkg)

<script src="https://unpkg.com/@ryniaubenpm2/incidunt-sunt-provident"></script>
import @ryniaubenpm2/incidunt-sunt-provident, { FetchError } from 'https://unpkg.com/@ryniaubenpm2/incidunt-sunt-provident/dist/@ryniaubenpm2/incidunt-sunt-provident.esm.min.js'

Why?

Less Boilerplate

Even though the Fetch API is significantly nicer to work with than XHR, it still quickly becomes verbose to do simple tasks. To create a relatively simple POST request using JSON, fetch requires something like:

fetch('/api/peeps', {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    accept: 'application/json',
  },
  credentials: 'same-origin',
  body: JSON.stringify({
    name: 'James Brown',
  }),
}).then((res) => {
  if (res.ok) {
    return res.json()
  }

  const err = new Error(response.statusText)

  err.response = response
  err.status = response.status

  throw err
}).then((person) => {
  console.log(person)
}).catch(...)

With @ryniaubenpm2/incidunt-sunt-provident this simply becomes:

@ryniaubenpm2/incidunt-sunt-provident.post('/api/peeps', { name: 'James Brown' }).then((person) => {
  console.log(person)
}).catch(...)

Isomorphism & Full ESM Support

@ryniaubenpm2/incidunt-sunt-provident uses conditional exports to load Node or browser (and Deno) compatible ESM or CJS files. main and module are also set in package.json for compatibility with legacy Node and legacy build systems. In Node, the main entry point uses node-fetch, which needs to be installed manually. In all other environments, the main entry point uses fetch, Headers, URL, URLSearchParams and FormData defined in the global scope.

Internally, the ESM & CJS entry points use the same CJS files to prevent the dual package hazard. See the Node documentation for more information.

Package Exports

'@ryniaubenpm2/incidunt-sunt-provident'

The main entry point returns a @ryniaubenpm2/incidunt-sunt-provident instance. When using import, a named export FetchError is also exposed.

import @ryniaubenpm2/incidunt-sunt-provident, { FetchError } from '@ryniaubenpm2/incidunt-sunt-provident'
// or
const @ryniaubenpm2/incidunt-sunt-provident = require('@ryniaubenpm2/incidunt-sunt-provident')

The browser/Deno version is created using (see factory for details):

export default factory({
  credentials: 'same-origin',
  response: 'json',
  fetch,
  Headers,
})

The Node version is created using:

import fetch from 'node-fetch'

export default factory({
  credentials: 'same-origin',
  response: 'json',
  fetch,
  Headers: fetch.Headers,
})

The main entry exposes most TypeScript types:

import { Options, Rek } from '@ryniaubenpm2/incidunt-sunt-provident'

'@ryniaubenpm2/incidunt-sunt-provident/error'

Exports the FetchError. Both import and require will load ./dist/error.cjs in all environments.

// import
import FetchError from '@ryniaubenpm2/incidunt-sunt-provident/error'
// require
const FetchError = require('@ryniaubenpm2/incidunt-sunt-provident/error')
// legacy
const FetchError = require('@ryniaubenpm2/incidunt-sunt-provident/dist/error.cjs')

'@ryniaubenpm2/incidunt-sunt-provident/factory'

Exports the factory function that creates @ryniaubenpm2/incidunt-sunt-provident instances with new defaults. Both import and require will load ./dist/factory.cjs in all environments.

import factory from '@ryniaubenpm2/incidunt-sunt-provident/factory'
// require
const factory = require('@ryniaubenpm2/incidunt-sunt-provident/factory')
// legacy
const factory = require('@ryniaubenpm2/incidunt-sunt-provident/dist/factory.cjs')

The factory entry also exposes TypeScript types:

import { Options, Rek } from '@ryniaubenpm2/incidunt-sunt-provident'

CDN (Unpkg)

On top of CJS and ESM files, bundles to be consumed through unpkg.com are built into ./dist/. The unpkg field in package.json points at the minified UMD build. This means:

<script src="https://unpkg.com/@ryniaubenpm2/incidunt-sunt-provident"></script>

is the same as

<script src="https://unpkg.com/@ryniaubenpm2/incidunt-sunt-provident/dist/@ryniaubenpm2/incidunt-sunt-provident.umd.min.js"></script>

To use the ES5 compatible UMD bundle:

<script src="https://unpkg.com/@ryniaubenpm2/incidunt-sunt-provident/dist/@ryniaubenpm2/incidunt-sunt-provident.umd.es5.min.js"></script>

The ESM bundle can be imported from a JS file:

import @ryniaubenpm2/incidunt-sunt-provident, { FetchError } from 'https://unpkg.com/@ryniaubenpm2/incidunt-sunt-provident/dist/@ryniaubenpm2/incidunt-sunt-provident.esm.min.js'

The following bundles are available in the dist folder:

  • ./dist/@ryniaubenpm2/incidunt-sunt-provident.esm.js - ESM bundle
  • ./dist/@ryniaubenpm2/incidunt-sunt-provident.esm.min.js - Minified ESM bundle
  • ./dist/@ryniaubenpm2/incidunt-sunt-provident.umd.js - UMD bundle
  • ./dist/@ryniaubenpm2/incidunt-sunt-provident.umd.min.js - Minified UMD bundle
  • ./dist/@ryniaubenpm2/incidunt-sunt-provident.umd.es5.js - ES5 compatible UMD bundle
  • ./dist/@ryniaubenpm2/incidunt-sunt-provident.umd.es5.min.js - Minified ES5 compatible UMD bundle

API

Usage

@ryniaubenpm2/incidunt-sunt-provident(url, options?)

Makes a request with fetch and returns a parsed response body or the Response (depending on the response option). If res.ok is not true, an error is thrown. See options below for differences to native fetch options.

@ryniaubenpm2/incidunt-sunt-provident('/url').then(json => { ... })
@ryniaubenpm2/incidunt-sunt-provident('/url', { response: 'text' }).then(text => { ... })
@ryniaubenpm2/incidunt-sunt-provident('/url', { body: { plain: 'object' }, method: 'post' }).then(json => { ... })
@ryniaubenpm2/incidunt-sunt-provident[method](url, body?, options?)

@ryniaubenpm2/incidunt-sunt-provident has convenience methods for all relevant HTTP request methods. They set the correct option.method and have an extra body argument when the request can send bodies (the body argument overwrites options.body).

  • @ryniaubenpm2/incidunt-sunt-provident.delete(url, options?)
  • @ryniaubenpm2/incidunt-sunt-provident.get(url, options?)
  • @ryniaubenpm2/incidunt-sunt-provident.head(url, options?)
  • @ryniaubenpm2/incidunt-sunt-provident.patch(url, body?, options?)
  • @ryniaubenpm2/incidunt-sunt-provident.post(url, body?, options?)
  • @ryniaubenpm2/incidunt-sunt-provident.put(url, body?, options?)
@ryniaubenpm2/incidunt-sunt-provident.delete('/api/peeps/1337')
// is the same as
@ryniaubenpm2/incidunt-sunt-provident('/api/peeps/1337', { method: 'DELETE' })

@ryniaubenpm2/incidunt-sunt-provident.post('/api/peeps/14', { name: 'Max Powers' })
// is the same as
@ryniaubenpm2/incidunt-sunt-provident('/api/peeps/14', { method: 'POST', body: { name: 'Max Powers' } })

Options

@ryniaubenpm2/incidunt-sunt-provident supports three arguments on top of the default fetch options: baseUrl, response and searchParams. It also handles body differently to native fetch().

Options passed to @ryniaubenpm2/incidunt-sunt-provident will be merged with the defaults defined in the factory.

If a string is passed as option argument, a new object is created with response set to that string.

@ryniaubenpm2/incidunt-sunt-provident('/', 'text')
// is the same
@ryniaubenpm2/incidunt-sunt-provident('/', { response: 'text' })
baseUrl

A URL that relative paths will be resolved against.

Setting this in defaults is very useful for SSR and similar.

body

Depending on the type of body passed, it could be converted to a JSON string and the content-type header could be removed or set

  • FormData || URLSearchParams: body will not be modified but content-type will be unset (setting content-type prevents the browser setting content-type with the boundary expression used to delimit form fields in the request body).
  • ArrayBuffer || Blob || DataView || ReadableStream: Neither body nor content-type will be modified.
  • All other (object) types: body will be converted to a JSON string, and content-type will be set to application/json (even if it is already set).
headers

Since default headers are merged with headers passed as options and it requires significantly more logic to merge Header instances, headers are expected to be passed as plain objects.

If Headers are already used, they can be converted to plain objects with:

Object.fromEntries(headers.entries())
response

Sets how to parse the response body. It needs to be either a valid Body read method name, a function accepting the response or falsy if the response should be returned without parsing the body. In the @ryniaubenpm2/incidunt-sunt-provident instance returned by the main entry, response defaults to 'json'.

typeof await @ryniaubenpm2/incidunt-sunt-provident('/url') === 'object' // is JSON

typeof await @ryniaubenpm2/incidunt-sunt-provident('/url', { response: 'text' }) === 'string'

await @ryniaubenpm2/incidunt-sunt-provident('/url', { response: 'blob' }) instanceof Blob

// will throw
@ryniaubenpm2/incidunt-sunt-provident('/url', { response: 'invalid response' })

await @ryniaubenpm2/incidunt-sunt-provident('/url', { response: false }) instanceof Response

await @ryniaubenpm2/incidunt-sunt-provident('/url', { response: (res) => 'return value' }) === 'return value'

Depending on the response, the following Accept header will be set:

  • arrayBuffer: */*
  • blob: */*
  • formData: multipart/form-data
  • json: application/json
  • text: text/*
searchParams

A valid URLSearchParams constructor argument used to add a query string to the URL. A query string already present in the url passed to @ryniaubenpm2/incidunt-sunt-provident will be overwritten.

@ryniaubenpm2/incidunt-sunt-provident('/url', { searchParams: 'foo=1&bar=2' })
@ryniaubenpm2/incidunt-sunt-provident('/url', { searchParams: '?foo=1&bar=2' })

// sequence of pairs
@ryniaubenpm2/incidunt-sunt-provident('/url', { searchParams: [['foo', '1'], ['bar', '2']] })

// plain object
@ryniaubenpm2/incidunt-sunt-provident('/url', { searchParams: { foo: 1, bar: 2 } })

// URLSearchParams
@ryniaubenpm2/incidunt-sunt-provident('/url', { searchParams: new URLSearchParams({ foo: 1, bar: 2 }) })

.extend(defaults)

The extend method will return a new @ryniaubenpm2/incidunt-sunt-provident instance with arguments merged with the previous values.

const myRek = @ryniaubenpm2/incidunt-sunt-provident.extend({ baseUrl: 'http://localhost:1337' })
const myRek = @ryniaubenpm2/incidunt-sunt-provident.extend({ credentials: 'omit', fetch: myFetch })

Factory

import factory from '@ryniaubenpm2/incidunt-sunt-provident/factory'
// or
const factory = require('@ryniaubenpm2/incidunt-sunt-provident/factory')

const myRek = factory({
  headers: {
    accept: 'application/html',
    'content-type': 'application/x-www-form-urlencoded',
  },
  credentials: 'omit',
  fetch: fancyfetch,
  Headers: FancyHeaders,
})

myRek()
myRek.delete()
myRek.patch()

TypeScript

The main entry exposes most types

import { Defaults, Options, Rek } from '@ryniaubenpm2/incidunt-sunt-provident'

Credits

Very big thank you to kolodny for releasing the NPM name!

Keywords

FAQs

Package last updated on 01 May 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc