All Projects → lukechilds → Cacheable Request

lukechilds / Cacheable Request

Licence: mit
Wrap native HTTP requests with RFC compliant cache support

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Cacheable Request

Apipeline
Feature-rich and pluggable offline-first API wrapper for all your javascript environements ! Easily wire-up your API and make your app work offline in minutes.
Stars: ✭ 92 (-57.8%)
Mutual labels:  wrapper, request
Bus
Bus 是一个基础框架、服务套件,它基于Java8编写,参考、借鉴了大量已有框架、组件的设计,可以作为后端服务的开发基础中间件。代码简洁,架构清晰,非常适合学习使用。
Stars: ✭ 253 (+16.06%)
Mutual labels:  wrapper, cache
Pokeapi Js Wrapper
PokeAPI browser wrapper, fully async with built-in cache
Stars: ✭ 129 (-40.83%)
Mutual labels:  wrapper, cache
Daisynet
1. - Alamofire与Cache封装 , 更容易存储请求数据. 2. - 封装Alamofire下载,使用更方便
Stars: ✭ 331 (+51.83%)
Mutual labels:  cache, request
Netclient Ios
Versatile HTTP Networking in Swift
Stars: ✭ 117 (-46.33%)
Mutual labels:  cache, request
Guzzle Advanced Throttle
A Guzzle middleware that can throttle requests according to (multiple) defined rules. It is also possible to define a caching strategy, e.g. get the response from cache when the rate limit is exceeded or always get a cached value to spare your rate limits. Using wildcards in host names is also supported.
Stars: ✭ 120 (-44.95%)
Mutual labels:  cache, request
Http Cache Semantics
RFC 7234 in JavaScript. Parses HTTP headers to correctly compute cacheability of responses, even in complex cases
Stars: ✭ 169 (-22.48%)
Mutual labels:  rfc, cache
Flutter wrapper
Flutter execution wrapper which keeps the flutter version in sync for each project
Stars: ✭ 195 (-10.55%)
Mutual labels:  wrapper
Redis Cache
A persistent object cache backend for WordPress powered by Redis. Supports Predis, PhpRedis, Credis, HHVM, replication and clustering.
Stars: ✭ 205 (-5.96%)
Mutual labels:  cache
Golib
Go Library [DEPRECATED]
Stars: ✭ 194 (-11.01%)
Mutual labels:  cache
Masterchief
C# 开发辅助类库,和士官长一样身经百战且越战越勇的战争机器,能力无人能出其右。
Stars: ✭ 190 (-12.84%)
Mutual labels:  cache
Scaffeine
Thin Scala wrapper for Caffeine (https://github.com/ben-manes/caffeine)
Stars: ✭ 195 (-10.55%)
Mutual labels:  cache
Node Fb Messenger
✉️ Facebook Messenger Platform Node.js API Wrapper
Stars: ✭ 206 (-5.5%)
Mutual labels:  wrapper
Mailjet Apiv3 Php
[API v3] Mailjet PHP Wrapper
Stars: ✭ 194 (-11.01%)
Mutual labels:  wrapper
Fuse
The simple generic LRU memory/disk cache for Android written in Kotlin
Stars: ✭ 212 (-2.75%)
Mutual labels:  cache
Drone Cache
A Drone plugin for caching current workspace files between builds to reduce your build times
Stars: ✭ 194 (-11.01%)
Mutual labels:  cache
Springboot Examples
spring boot 实践系列
Stars: ✭ 216 (-0.92%)
Mutual labels:  cache
Cachingframework.redis
Distributed caching based on StackExchange.Redis and Redis. Includes support for tagging and is cluster-compatible.
Stars: ✭ 209 (-4.13%)
Mutual labels:  cache
Immortalplayer
Free audio/video player component for Android with cache, FTP, peering, hw accel, background play, pseudo-streaming and more...
Stars: ✭ 204 (-6.42%)
Mutual labels:  cache
Java Library Examples
💪 example of common used libraries and frameworks, programming required, don't fork man.
Stars: ✭ 204 (-6.42%)
Mutual labels:  cache

cacheable-request

Wrap native HTTP requests with RFC compliant cache support

Build Status Coverage Status npm npm

RFC 7234 compliant HTTP caching for native Node.js HTTP/HTTPS requests. Caching works out of the box in memory or is easily pluggable with a wide range of storage adapters.

Note: This is a low level wrapper around the core HTTP modules, it's not a high level request library.

Features

  • Only stores cacheable responses as defined by RFC 7234
  • Fresh cache entries are served directly from cache
  • Stale cache entries are revalidated with If-None-Match/If-Modified-Since headers
  • 304 responses from revalidation requests use cached body
  • Updates Age header on cached responses
  • Can completely bypass cache on a per request basis
  • In memory cache by default
  • Official support for Redis, MongoDB, SQLite, PostgreSQL and MySQL storage adapters
  • Easily plug in your own or third-party storage adapters
  • If DB connection fails, cache is automatically bypassed (disabled by default)
  • Adds cache support to any existing HTTP code with minimal changes
  • Uses http-cache-semantics internally for HTTP RFC 7234 compliance

Install

npm install cacheable-request

Usage

const http = require('http');
const CacheableRequest = require('cacheable-request');

// Then instead of
const req = http.request('http://example.com', cb);
req.end();

// You can do
const cacheableRequest = new CacheableRequest(http.request);
const cacheReq = cacheableRequest('http://example.com', cb);
cacheReq.on('request', req => req.end());
// Future requests to 'example.com' will be returned from cache if still valid

// You pass in any other http.request API compatible method to be wrapped with cache support:
const cacheableRequest = new CacheableRequest(https.request);
const cacheableRequest = new CacheableRequest(electron.net);

Storage Adapters

cacheable-request uses Keyv to support a wide range of storage adapters.

For example, to use Redis as a cache backend, you just need to install the official Redis Keyv storage adapter:

npm install @keyv/redis

And then you can pass CacheableRequest your connection string:

const cacheableRequest = new CacheableRequest(http.request, 'redis://user:[email protected]:6379');

View all official Keyv storage adapters.

Keyv also supports anything that follows the Map API so it's easy to write your own storage adapter or use a third-party solution.

e.g The following are all valid storage adapters

const storageAdapter = new Map();
// or
const storageAdapter = require('./my-storage-adapter');
// or
const QuickLRU = require('quick-lru');
const storageAdapter = new QuickLRU({ maxSize: 1000 });

const cacheableRequest = new CacheableRequest(http.request, storageAdapter);

View the Keyv docs for more information on how to use storage adapters.

API

new cacheableRequest(request, [storageAdapter])

Returns the provided request function wrapped with cache support.

request

Type: function

Request function to wrap with cache support. Should be http.request or a similar API compatible request function.

storageAdapter

Type: Keyv storage adapter
Default: new Map()

A Keyv storage adapter instance, or connection string if using with an official Keyv storage adapter.

Instance

cacheableRequest(opts, [cb])

Returns an event emitter.

opts

Type: object, string

  • Any of the default request functions options.
  • Any http-cache-semantics options.
  • Any of the following:
opts.cache

Type: boolean
Default: true

If the cache should be used. Setting this to false will completely bypass the cache for the current request.

opts.strictTtl

Type: boolean
Default: false

If set to true once a cached resource has expired it is deleted and will have to be re-requested.

If set to false (default), after a cached resource's TTL expires it is kept in the cache and will be revalidated on the next request with If-None-Match/If-Modified-Since headers.

opts.maxTtl

Type: number
Default: undefined

Limits TTL. The number represents milliseconds.

opts.automaticFailover

Type: boolean
Default: false

When set to true, if the DB connection fails we will automatically fallback to a network request. DB errors will still be emitted to notify you of the problem even though the request callback may succeed.

opts.forceRefresh

Type: boolean
Default: false

Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a new request and override the cache instead.

cb

Type: function

The callback function which will receive the response as an argument.

The response can be either a Node.js HTTP response stream or a responselike object. The response will also have a fromCache property set with a boolean value.

.on('request', request)

request event to get the request object of the request.

Note: This event will only fire if an HTTP request is actually made, not when a response is retrieved from cache. However, you should always handle the request event to end the request and handle any potential request errors.

.on('response', response)

response event to get the response object from the HTTP request or cache.

.on('error', error)

error event emitted in case of an error with the cache.

Errors emitted here will be an instance of CacheableRequest.RequestError or CacheableRequest.CacheError. You will only ever receive a RequestError if the request function throws (normally caused by invalid user input). Normal request errors should be handled inside the request event.

To properly handle all error scenarios you should use the following pattern:

cacheableRequest('example.com', cb)
  .on('error', err => {
    if (err instanceof CacheableRequest.CacheError) {
      handleCacheError(err); // Cache error
    } else if (err instanceof CacheableRequest.RequestError) {
      handleRequestError(err); // Request function thrown
    }
  })
  .on('request', req => {
    req.on('error', handleRequestError); // Request error emitted
    req.end();
  });

Note: Database connection errors are emitted here, however cacheable-request will attempt to re-request the resource and bypass the cache on a connection error. Therefore a database connection error doesn't necessarily mean the request won't be fulfilled.

License

MIT © Luke Childs

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].