• This repository has been archived on 12/Jun/2022
  • Stars
    star
    384
  • Rank 111,726 (Top 3 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 7 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Get in loser, we're making requests!

make-fetch-happen npm version license Travis AppVeyor Coverage Status

make-fetch-happen is a Node.js library that wraps node-fetch-npm with additional features node-fetch doesn't intend to include, including HTTP Cache support, request pooling, proxies, retries, and more!

Install

$ npm install --save make-fetch-happen

Table of Contents

Example

const fetch = require('make-fetch-happen').defaults({
  cacheManager: './my-cache' // path where cache will be written (and read)
})

fetch('https://registry.npmjs.org/make-fetch-happen').then(res => {
  return res.json() // download the body as JSON
}).then(body => {
  console.log(`got ${body.name} from web`)
  return fetch('https://registry.npmjs.org/make-fetch-happen', {
    cache: 'no-cache' // forces a conditional request
  })
}).then(res => {
  console.log(res.status) // 304! cache validated!
  return res.json().then(body => {
    console.log(`got ${body.name} from cache`)
  })
})

Features

  • Builds around node-fetch for the core fetch API implementation
  • Request pooling out of the box
  • Quite fast, really
  • Automatic HTTP-semantics-aware request retries
  • Cache-fallback automatic "offline mode"
  • Proxy support (http, https, socks, socks4, socks5)
  • Built-in request caching following full HTTP caching rules (Cache-Control, ETag, 304s, cache fallback on error, etc).
  • Customize cache storage with any Cache API-compliant Cache instance. Cache to Redis!
  • Node.js Stream support
  • Transparent gzip and deflate support
  • Subresource Integrity support
  • Literally punches nazis
  • (PENDING) Range request caching and resuming

Contributing

The make-fetch-happen team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The Contributor Guide has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear.

All participants and maintainers in this project are expected to follow Code of Conduct, and just generally be excellent to each other.

Please refer to the Changelog for project history details, too.

Happy hacking!

API

> fetch(uriOrRequest, [opts]) -> Promise<Response>

This function implements most of the fetch API: given a uri string or a Request instance, it will fire off an http request and return a Promise containing the relevant response.

If opts is provided, the node-fetch-specific options will be passed to that library. There are also additional options specific to make-fetch-happen that add various features, such as HTTP caching, integrity verification, proxy support, and more.

Example
fetch('https://google.com').then(res => res.buffer())

> fetch.defaults([defaultUrl], [defaultOpts])

Returns a new fetch function that will call make-fetch-happen using defaultUrl and defaultOpts as default values to any calls.

A defaulted fetch will also have a .defaults() method, so they can be chained.

Example
const fetch = require('make-fetch-happen').defaults({
  cacheManager: './my-local-cache'
})

fetch('https://registry.npmjs.org/make-fetch-happen') // will always use the cache

> node-fetch options

The following options for node-fetch are used as-is:

  • method
  • body
  • redirect
  • follow
  • timeout
  • compress
  • size

These other options are modified or augmented by make-fetch-happen:

  • headers - Default User-Agent set to make-fetch happen. Connection is set to keep-alive or close automatically depending on opts.agent.
  • agent
    • If agent is null, an http or https Agent will be automatically used. By default, these will be http.globalAgent and https.globalAgent.
    • If opts.proxy is provided and opts.agent is null, the agent will be set to an appropriate proxy-handling agent.
    • If opts.agent is an object, it will be used as the request-pooling agent argument for this request.
    • If opts.agent is false, it will be passed as-is to the underlying request library. This causes a new Agent to be spawned for every request.

For more details, see the documentation for node-fetch itself.

> make-fetch-happen options

make-fetch-happen augments the node-fetch API with additional features available through extra options. The following extra options are available:

> opts.cacheManager

Either a String or a Cache. If the former, it will be assumed to be a Path to be used as the cache root for cacache.

If an object is provided, it will be assumed to be a compliant Cache instance. Only Cache.match(), Cache.put(), and Cache.delete() are required. Options objects will not be passed in to match() or delete().

By implementing this API, you can customize the storage backend for make-fetch-happen itself -- for example, you could implement a cache that uses redis for caching, or simply keeps everything in memory. Most of the caching logic exists entirely on the make-fetch-happen side, so the only thing you need to worry about is reading, writing, and deleting, as well as making sure fetch.Response objects are what gets returned.

You can refer to cache.js in the make-fetch-happen source code for a reference implementation.

NOTE: Requests will not be cached unless their response bodies are consumed. You will need to use one of the res.json(), res.buffer(), etc methods on the response, or drain the res.body stream, in order for it to be written.

The default cache manager also adds the following headers to cached responses:

  • X-Local-Cache: Path to the cache the content was found in
  • X-Local-Cache-Key: Unique cache entry key for this response
  • X-Local-Cache-Hash: Specific integrity hash for the cached entry
  • X-Local-Cache-Time: UTCString of the cache insertion time for the entry

Using cacache, a call like this may be used to manually fetch the cached entry:

const h = response.headers
cacache.get(h.get('x-local-cache'), h.get('x-local-cache-key'))

// grab content only, directly:
cacache.get.byDigest(h.get('x-local-cache'), h.get('x-local-cache-hash'))
Example
fetch('https://registry.npmjs.org/make-fetch-happen', {
  cacheManager: './my-local-cache'
}) // -> 200-level response will be written to disk

fetch('https://npm.im/cacache', {
  cacheManager: new MyCustomRedisCache(process.env.PORT)
}) // -> 200-level response will be written to redis

A possible (minimal) implementation for MyCustomRedisCache:

const bluebird = require('bluebird')
const redis = require("redis")
bluebird.promisifyAll(redis.RedisClient.prototype)
class MyCustomRedisCache {
  constructor (opts) {
    this.redis = redis.createClient(opts)
  }
  match (req) {
    return this.redis.getAsync(req.url).then(res => {
      if (res) {
        const parsed = JSON.parse(res)
        return new fetch.Response(parsed.body, {
          url: req.url,
          headers: parsed.headers,
          status: 200
        })
      }
    })
  }
  put (req, res) {
    return res.buffer().then(body => {
      return this.redis.setAsync(req.url, JSON.stringify({
        body: body,
        headers: res.headers.raw()
      }))
    }).then(() => {
      // return the response itself
      return res
    })
  }
  'delete' (req) {
    return this.redis.unlinkAsync(req.url)
  }
}

> opts.cache

This option follows the standard fetch API cache option. This option will do nothing if opts.cacheManager is null. The following values are accepted (as strings):

  • default - Fetch will inspect the HTTP cache on the way to the network. If there is a fresh response it will be used. If there is a stale response a conditional request will be created, and a normal request otherwise. It then updates the HTTP cache with the response. If the revalidation request fails (for example, on a 500 or if you're offline), the stale response will be returned.
  • no-store - Fetch behaves as if there is no HTTP cache at all.
  • reload - Fetch behaves as if there is no HTTP cache on the way to the network. Ergo, it creates a normal request and updates the HTTP cache with the response.
  • no-cache - Fetch creates a conditional request if there is a response in the HTTP cache and a normal request otherwise. It then updates the HTTP cache with the response.
  • force-cache - Fetch uses any response in the HTTP cache matching the request, not paying attention to staleness. If there was no response, it creates a normal request and updates the HTTP cache with the response.
  • only-if-cached - Fetch uses any response in the HTTP cache matching the request, not paying attention to staleness. If there was no response, it returns a network error. (Can only be used when requestโ€™s mode is "same-origin". Any cached redirects will be followed assuming requestโ€™s redirect mode is "follow" and the redirects do not violate requestโ€™s mode.)

(Note: option descriptions are taken from https://fetch.spec.whatwg.org/#http-network-or-cache-fetch)

Example
const fetch = require('make-fetch-happen').defaults({
  cacheManager: './my-cache'
})

// Will error with ENOTCACHED if we haven't already cached this url
fetch('https://registry.npmjs.org/make-fetch-happen', {
  cache: 'only-if-cached'
})

// Will refresh any local content and cache the new response
fetch('https://registry.npmjs.org/make-fetch-happen', {
  cache: 'reload'
})

// Will use any local data, even if stale. Otherwise, will hit network.
fetch('https://registry.npmjs.org/make-fetch-happen', {
  cache: 'force-cache'
})

> opts.proxy

A string or url.parse-d URI to proxy through. Different Proxy handlers will be used depending on the proxy's protocol.

Additionally, process.env.HTTP_PROXY, process.env.HTTPS_PROXY, and process.env.PROXY are used if present and no opts.proxy value is provided.

(Pending) process.env.NO_PROXY may also be configured to skip proxying requests for all, or specific domains.

Example
fetch('https://registry.npmjs.org/make-fetch-happen', {
  proxy: 'https://corporate.yourcompany.proxy:4445'
})

fetch('https://registry.npmjs.org/make-fetch-happen', {
  proxy: {
    protocol: 'https:',
    hostname: 'corporate.yourcompany.proxy',
    port: 4445
  }
})

> opts.noProxy

If present, should be a comma-separated string or an array of domain extensions that a proxy should not be used for.

This option may also be provided through process.env.NO_PROXY.

> opts.ca, opts.cert, opts.key, opts.strictSSL

These values are passed in directly to the HTTPS agent and will be used for both proxied and unproxied outgoing HTTPS requests. They mostly correspond to the same options the https module accepts, which will be themselves passed to tls.connect(). opts.strictSSL corresponds to rejectUnauthorized.

> opts.localAddress

Passed directly to http and https request calls. Determines the local address to bind to.

> opts.maxSockets

Default: 15

Maximum number of active concurrent sockets to use for the underlying Http/Https/Proxy agents. This setting applies once per spawned agent.

15 is probably a pretty good value for most use-cases, and balances speed with, uh, not knocking out people's routers. ๐Ÿค“

> opts.retry

An object that can be used to tune request retry settings. Retries will only be attempted on the following conditions:

  • Request method is NOT POST AND
  • Request status is one of: 408, 420, 429, or any status in the 500-range. OR
  • Request errored with ECONNRESET, ECONNREFUSED, EADDRINUSE, ETIMEDOUT, or the fetch error request-timeout.

The following are worth noting as explicitly not retried:

  • getaddrinfo ENOTFOUND and will be assumed to be either an unreachable domain or the user will be assumed offline. If a response is cached, it will be returned immediately.
  • ECONNRESET currently has no support for restarting. It will eventually be supported but requires a bit more juggling due to streaming.

If opts.retry is false, it is equivalent to {retries: 0}

If opts.retry is a number, it is equivalent to {retries: num}

The following retry options are available if you want more control over it:

  • retries
  • factor
  • minTimeout
  • maxTimeout
  • randomize

For details on what each of these do, refer to the retry documentation.

Example
fetch('https://flaky.site.com', {
  retry: {
    retries: 10,
    randomize: true
  }
})

fetch('http://reliable.site.com', {
  retry: false
})

fetch('http://one-more.site.com', {
  retry: 3
})

> opts.onRetry

A function called whenever a retry is attempted.

Example
fetch('https://flaky.site.com', {
  onRetry() {
    console.log('we will retry!')
  }
})

> opts.integrity

Matches the response body against the given Subresource Integrity metadata. If verification fails, the request will fail with an EINTEGRITY error.

integrity may either be a string or an ssri Integrity-like.

Example
fetch('https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-1.0.0.tgz', {
  integrity: 'sha1-o47j7zAYnedYFn1dF/fR9OV3z8Q='
}) // -> ok

fetch('https://malicious-registry.org/make-fetch-happen/-/make-fetch-happen-1.0.0.tgz', {
  integrity: 'sha1-o47j7zAYnedYFn1dF/fR9OV3z8Q='
}) // Error: EINTEGRITY

Message From Our Sponsors

More Repositories

1

npx

execute npm package binaries (moved)
JavaScript
2,625
star
2

miette

Fancy extension for std::error::Error with pretty, detailed diagnostic printing.
Rust
2,005
star
3

big-brain

Utility AI library for the Bevy game engine
Rust
1,032
star
4

cacache-rs

A high-performance, concurrent, content-addressable disk cache, with support for both sync and async APIs. ๐Ÿ’ฉ๐Ÿ’ต but for your ๐Ÿฆ€
Rust
529
star
5

cipm

standalone ci-oriented package installer for npm projects (moved)
JavaScript
400
star
6

pacote

programmatic npm package and metadata downloader (moved!)
JavaScript
280
star
7

cacache

๐Ÿ’ฉ๐Ÿ’ต but for your data. If you've got the hash, we've got the cache โ„ข (moved)
JavaScript
240
star
8

chanl

Portable channel-based concurrency for Common Lisp
Common Lisp
164
star
9

mona

Composable parsing for JavaScript
JavaScript
152
star
10

rust-notes

Personal notes while learning Rust. Mainly documenting pain points along the way.
145
star
11

maybe-hugs

Polyglot implementations of conditional hugging
OCaml
114
star
12

proposal-as-patterns

`as` destructuring patterns
105
star
13

sheeple

Cheeky prototypes for Common Lisp
Common Lisp
99
star
14

pattycake

playground for pattern matching api
JavaScript
98
star
15

ssri

Standard Subresource Integrity library for Node.js
JavaScript
82
star
16

json-parse-better-errors

get better errors
JavaScript
67
star
17

squirl

Common Lisp port of the Chipmunk 2d physics library
Common Lisp
53
star
18

supports-color

Detects whether a terminal supports color, and gives details about that support
Rust
42
star
19

figgy-pudding

Cascading, controlled-visibility options object management.
JavaScript
39
star
20

genfun

Prototype-friendly multimethods for JavaScript.
JavaScript
38
star
21

ssri-rs

Rusty implementation of Subresource Integrity
Rust
38
star
22

can.viewify

require() mustache and ejs modules as compiled CanJS views
JavaScript
37
star
23

protoduck

Duck typing for the most serious of ducks.
JavaScript
35
star
24

chillax

CouchDB abstraction layer for Common Lisp
Common Lisp
34
star
25

cl-openal

Common Lisp bindings for the OpenAL audio library.
Common Lisp
34
star
26

conserv

Common Lisp
31
star
27

memento-mori

Robustness through actors, for Common Lisp
Common Lisp
31
star
28

talks

Notes and slides for all my talks
JavaScript
26
star
29

until-it-dies

A batteries-included game engine.
Common Lisp
25
star
30

supports-hyperlinks

Detect whether the current terminal supports rendering hyperlinks
Rust
25
star
31

matrix-curious

FAQ and resources for those curious about joining the Matrix network!
23
star
32

sykobot

An IRC bot from another universe. No, really.
Common Lisp
21
star
33

turron

Rusty NuGet client
Rust
20
star
34

npm-pick-manifest

Standard manifest picker/semver resolver for npm
JavaScript
20
star
35

cl-ffmpeg

CFFI bindings for FFMPEG
Common Lisp
19
star
36

proposal-collection-literals

[WITHDRAWN] tc39 proposal for custom collection literals
18
star
37

cl-devil

Common Lisp bindings for DevIL
Common Lisp
16
star
38

okimdone

tells you when it's done
Shell
15
star
39

srisum-rs

Compute and check subresource integrity digests.
Rust
14
star
40

thisdiagnostic

Add nice user-facing diagnostics to your errors without being weird about it.
Rust
14
star
41

is_ci

Super lightweight and dead-simple CI detection.
Rust
12
star
42

common-worm

A simple, hackish version of the classic snake game, written in Common Lisp
Common Lisp
12
star
43

supports-unicode

Detects whether a terminal supports unicode.
Rust
12
star
44

nanotubes

Fancy websocket wrapper for Rust
Rust
12
star
45

srisum

Compute and check Subresource Integrity digests.
JavaScript
11
star
46

DWG.Directories

Standard directories for .NET
10
star
47

cadr

content-addressable filesystem snapshots
JavaScript
10
star
48

protocols

Multi-type protocol-based polymorphism
JavaScript
10
star
49

cl-speedy-queue

Lightweight, optimized queue implementation for CL
Common Lisp
9
star
50

playwright

Like Erlang, but not
JavaScript
9
star
51

sykosomatic

Cooperative storytelling
Common Lisp
7
star
52

cond

Restartable error handling system for JavaScript
JavaScript
7
star
53

destealify

Browserify transform for processing StealJS modules
JavaScript
7
star
54

bacon-browser

Utility library for higher-level, declarative interaction with various bits of browser-level events and features.
JavaScript
7
star
55

sykosomatic-legacy

text-based online game engine
Common Lisp
7
star
56

shepherdb

A Sheeple-based persistent object store.
Common Lisp
6
star
57

clutter

nothing to see here
Common Lisp
6
star
58

facile

CouchDB view server for Factor
Factor
6
star
59

fl-protocols

fantasy-land specification bridge for @zkat/protocols
JavaScript
6
star
60

electron-collider

Rust
5
star
61

my-precious

a local package archive, of our own
JavaScript
5
star
62

checksum-stream

Calculates and/or checks data coming through a stream and emits the digest before stream end.
JavaScript
5
star
63

cl-form

Generic form validation utility for CL
Common Lisp
5
star
64

common-brick

Breakout clone with "realistic" physics.
Common Lisp
4
star
65

surf-middleware-cache

http caching middleware for the Surf http client
Rust
4
star
66

specificity

Runnable specifications for Common Lisp
4
star
67

friendfavor

Find out what your friends think of something -- or someone!
Common Lisp
4
star
68

shortening

The personal URL shortener.
Common Lisp
3
star
69

kallisti

kallisti
Rust
3
star
70

clutterscript

Pay this no heed, I'm just learning stuff.
JavaScript
3
star
71

cl-event2

libevent2 bindings for Common Lisp
Common Lisp
3
star
72

yashmup

Toy project -- writing a shmup in CL
Common Lisp
3
star
73

test

just a place to test random github shit
2
star
74

marina

placeholder for programming language
2
star
75

mona-csv

simple mona-based csv parser
JavaScript
1
star
76

proto

Alternative to JavaScript's `new`.
Makefile
1
star
77

dynvar

Dynamic variables for JS
JavaScript
1
star
78

protoduck-fl

fantasy-land specification bridge for protoduck
JavaScript
1
star
79

mona-json

mona-based JSON parser
JavaScript
1
star
80

mona-strings

String parsers for mona
JavaScript
1
star
81

logloc

Adds source location to console loggers
JavaScript
1
star
82

zkat

it me
1
star
83

node-otp

The Node.js Open Telecom Platform
1
star
84

fetch-cache

Cache API implementation + protocol
JavaScript
1
star
85

tswrp

JavaScript
1
star
86

chownr-rs

Like chown -r for Rust
Rust
1
star
87

presentations

various presentations
JavaScript
1
star
88

storychat

~~~ tell me a story <3 with your words ~~~
JavaScript
1
star
89

mona-combinators

Parser combinators for mona
JavaScript
1
star
90

fig-roll

rolls up your configs into a nice figgy pudding
1
star
91

chatoid

Toy chatroom using webrtc
JavaScript
1
star
92

ironsworn-mechanics

Various support utilities and some custom rendering for mechanics in Ironsworn-family games (Starforged, Sundered Isles, etc).
TypeScript
1
star
93

zkat.github.io

Web sight
TypeScript
1
star