npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ryniaubenpm2/incidunt-sunt-provident

v1.0.0

Published

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.

Downloads

14

Maintainers

mi762136mi762136

Keywords

schema@@toStringTagnamechannelvaluesECMAScript 2021lockfileES7termmkdirmimetypesbyteLengthlesscsssymlinksWeakSetcircularspawntypeofmapAsyncIteratortestingglobalinspectpackage manager_.extendes-shimsenvironmentqueryfunctionallanguageasciiinterruptschai[[Prototype]]emitbeanstalkgdprenvwatchFileArray.prototype.filterprototypepatchparsereseslint-pluginpicomatchTypedArraycheckshimchromelibphonenumbergettoolkitless mixinsReactiveExtensionseslintUint8ClampedArraycommandcallbindECMAScript 2019bcryptconsolequotemomentsyntaxerrorreact-hook-formhasOwnPropertyopensec2class-validatortrimLeftframeworkxdg-openexit-codeReactiveXsetstatelessyupwatchinggenericselmObject.getPrototypeOfdescriptorsbreakmime-dbdescriptorwhatwges2015workerapitextimporttimees2018makelogsameValueZeroextensionspinnerserrortypesafesharedprotoinstallerObject.definePropertyES2017styleflagvalidateutilitieszodflatopenerstyleguidecorses7Streamjshintlook-upprettyFunction.prototype.nameimportexportclassnamescss nestingObjectcmdWebSocketsmixinsdirlruexpressionECMAScript 3censorStreamsduplexl10nencryptionloadbalancingrm -rf$.extendstylingjasminenodejsserializercachefsreadableurlnested cssoncestylesheetwebString.prototype.trimenumerableshelldomutil.inspectcollectioneslintconfigcommandertsajaxrandomidentifiersstreamagentbindfastcopyrestfulemojiCSSArray.prototype.flattenpathsomeRegExp#flagspropertiesviewschemeparsehaswarningBigInt64Arraynodesimpledbmetadatabootstrap cssbufferswalkinggradients css3stdlibgroupphoneparentspromisesgetintrinsicjsdomInt32ArrayObservablespipeSymbol.toStringTagworkflowaccessorfind-upfindeventsloadingBigUint64ArraytslibObject.valuesmkdirsobjelectronexpressunicodetakeserializationhas-owncommand-linegroupBytyped arraypostcsspredictablemochakarmaerror-handlinginvariantrmdirswftypedfullquerystringECMAScript 2020sigtermcolourform-validationstarter__proto__react-hookseverycolorpyyamlnegative zerostateisConcatSpreadablestatusupcomputed-typesiterateinternalwordwrapbundlingprivateeslintpluginconfigbufferponyfillflatMaphookformexec0zeroidlerangeerrorInt8Arraystringifierreplayargvarrayhandlersawaitredactbundlerdotenvregularcloudfrontstringformattingcore-jsworkspace:*processwrapIteratorlengthdebugcss lessredux-toolkitarraybuffercjkregexFloat32Arraycss variablemergeECMAScript 5pruneWeakMapformdropdom-testing-librarylinttelephonenegativepluginhigher-orderhttpsmake dircurlArrayBuffer.prototype.sliceperformantkeyArrayBuffercryptdeep-clonewatcheditorhelperspropertyiamformatidboundcollection.es6dependency managerrm -frvalidArraymiddlewarebluebirdelbsettingsinputdeep-copyhooksregular expressionECMAScript 2016trimEndmatchterminaldefinevariablesdataViewobjectmapreducepromiseObject.keyslaunchfull-widthrecursiveaccessibilityreact-testing-libraryflattenreadablestreamconcurrencyUnderscoresyntaxassertcodesforEachkoreanwaitutilityES8es2016symbolsStyleSheetcall-bindclassesfile systemasynctaskgetPrototypeOfiterationomitirqvestECMAScript 2018superstructdeepclonemodulesES2015HyBicode pointsdescriptiontypeerrorscheme-validationawsArrayBuffer#slicea11yPushqueueMicrotaskES2023tapcloudwatchjavascriptbrowserfastifyECMAScript 2015starttesterreactPromiseString.prototype.matchAllMaphotstyled-componentsthrottlerestreusenumberpnpm9fastcloneRegExp.prototype.flagspreserve-symlinksartRxJSutilstreams2macosES2018authshrinkwraptestchinesemodulelinkbootstrap lesssymlinktrimgetterjestsetPrototypeOfreadtypedarraysexetrimRightspeedtouchArray.prototype.findLastgetoptfullwidthebsUint8ArrayexitdayjsprogressES2016jsdiffjQuerynativeurlsappbrowserslisttypescriptfixed-widthpackagesownthroatfindLastconcatpackageserializeclassnamefast-deep-copysymboldiffbyteECMAScript 6argspushparentindynamodbwebsiteexecutablekinesisjsxwriteproxyvarsjwtrapidruntimeTypeBoxhardlinkses-shim APIvariables in csslimit256requestfpscharacterspostcss-pluginrdshttpastfindupwindowswafES2019keysrouteruninstallES6columnsvpcisprefixspinnerlookloggingflagswritablepropmonoreporequireArray.prototype.flatMapcharactermatchAllmatchessharedarraybufferio-tsefficientless cssES5package.jsonpolyfillreduxtypeRxxdgestreestreamssorttoSortedxhrObject.entriesinferenceguidoutputfoldercssregexpregular expressionsloggermulti-packageslicedatalistenersstringifyqueuedebuggerminimalObject.isshebangwordbreakreduceryamlcoretoStringTagESglaciersigintWebSocketendpointfast-cloneintrinsicRFC-6455batchi18ninstallopenlazyes6autoscalingassertionpositivees8sides3endernopeprotobufprotocol-bufferstypanionsignalssearchsortedObject.assignESnextReflect.getPrototypeOfconsumedataviewes5browserlistcontainshashargumenttrimStartextraYAMLhasOwntapeimmutableJSONcolumnes2017sesttynpmcloudformationdefinePropertymobileqsFloat64Arraylimitedtc39Symbolincludesoptionfast-deep-clonespecprivate dataliveless compilercomparemimesafefunctionequalitygradients cssclonesqsjsonpathtostringtagECMAScript 7fluxxtermcryptoelasticachejsmkdirpbusyArray.prototype.containsinternal slotajv

Readme

@ryniaubenpm2/incidunt-sunt-provident

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

| Build | Unminified | Minified | Gzipped | | ---------------- | ---------- | -------- | ------- | | ESM bundle | 3.36 kB | 1.54 kB | 798 B | | UMD bundle | 3.87 kB | 1.71 kB | 873 B | | UMD bundle (ES5) | 4.12 kB | 1.86 kB | 894 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!