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

node-api-cache-proxy

v0.8.0

Published

Cache requests in nodejs

Downloads

251

Readme

Node API Cache Proxy

When API is down, work may be hard for front-end developer. Configure api cache to fallback REST API responses.

API not responding. “API not responding”

How it works?

  • Works as middleware for API calls
  • Save responses depending on address, headers and request payload
  • Serves cached data, when API is down

How to install

npm install --save node-api-cache-proxy

How to use

Minimal using Express:

var express = require('express')
var APICacheProxy = require('node-api-cache-proxy')

var app = express()
var apiCacheProxy = new APICacheProxy({
	apiUrl: 'http://destination-api-url.com',
	cacheDir: 'cache-api/',
	localURLReplace: function(url) {
		return url.replace('/api/', '/')
	}
})

app.use('/api', apiCacheProxy)

Sample using Express:

var express = require('express')
var APICacheProxy = require('node-api-cache-proxy')

var app = express()
var apiCacheProxy = new APICacheProxy({
	apiUrl: 'http://destination-backend-url.com',
	excludeRequestHeaders: [
		'Cookie', 'User-Agent', 'User-Agent', 'Referer', 'Origin', 'Host', 'DNT'
	],
	excludeRequestParams: ['_'],
	isValidResponse: function(requestEnvelope) {
		// this is default validation function, feel free to override it
		if (requestEnvelope.statusCode === 200) {
			return true;
		} else {
			return false;
		}
	},
	localURLReplace: function(url) {
		return url.replace('/api/', '/')
	}
})

app.use('/api', apiCacheProxy)

API

var apiCache = new APICache(config), config:

  • cacheEnabled {boolean}: When false, plugin will work as proxy, without caching.
  • apiUrl {string, required}: Proxy replaces protocol, domain part with apiUrl
  • cacheDir {string}: Directory to save requests
  • excludeRequestHeaders {array}: headers to omit when writing or reading cache file
  • excludeRequestParams {array}: usually cache parameter from your request address
  • localURLReplace(url: string) {function}: prepare url to API
  • isValidResponse {function(requestEnvelope: Object)}: Check if API response is valid or not.
    • when true is returned, request will be saved and ready to use
    • when false is returned, request won't be saved and cache entry will be served instead (if available)
  • timeout {object}: Milliseconds, helps terminating requests for really slow backends.

requestEnvelope format:

	{
		reqURL: 'http://my-api.local/method/route?action=sth',
		reqMethod: 'POST',
		reqHeaders: response.request.headers,
		reqBody: 'request=a&body=is&just=for&POST=PUT,etc:)',

		body: body,
		headers: response.headers,
		statusCode: response.statusCode,
		statusMessage: response.statusMessage,

		cacheDate: "2015-11-30 01:35:53",
		version: "0.6.1"
	}

Error Handling

Custom error handler, executed when API response doesn't pass isValidResponse test, and there is no cached response:

var apiCache = new APICacheProxy({...})
var app = express()

app.use('/api', function(req, res, next) {
	apiCacheProxy(req, res, next).catch(function(requestEnvelope) {
		res.status(requestEnvelope.statusCode).send(
			'<pre>' + requestEnvelope.body + '</pre>'
		)
	})
})

Handle case, when API response doesn't pass isValidResponse test but there is cached response:

var apiCache = new APICacheProxy({...})
var app = express()

app.use('/api', function(req, res, next) {
	apiCacheProxy(req, res, next).then(function(status) {
		if (status.dataSource === 'Cache') {
			console.warn('[' + status.envelope.reqMethod + '] ' + status.envelope.reqURL)
			console.warn('  API failure. Served: ' + status.filePath)
		}
	})
})

API data format support table

| Feature | Support | | --------------------- | ------------- | | text content | Yes | | deflate-text content | Yes | | gzip-text content | Yes | | binary content | No | | https | Yes | | POST, GET, PUT, ... | Yes |

Requirements

This module is maintained on node v20 LTS. It may work on older and newer node versions.