<commit_before>A simple API response caching middleware for Express/Node using plain-english durations.
=======

[![Build Status via Travis CI](https://travis-ci.org/kwhitley/apicache.svg?branch=master)](https://travis-ci.org/kwhitley/apicache)

## Why?

Because caching of simple data/responses should ALSO be simple.

This day and age, with less and less heavy lifting done on the server,
the most common thing we find ourselves doing is
letting the server power the API.  Whether the data is stored in Mongo, SQL,
CouchDB, or whatever - you get a request, you fetch the data, and you return
the data.  Sometimes these fetches are costly and you want to cache the response
so the next hit doesn't hammer your server.  This is why caching exists.

The problem is, with so many cache options, people are still left to fend for themselves
when it comes to implementation.  It often boils down to a manual process similar to the following:

1. Get the request
2. Check your cache for the key/url.
3. If found, intercept and output the cached version.
4. If not, do the work, cache it, and output.

You're still left wrapping the content of each request with this cache-checking mechanism.

Now it can be as simple as telling the request that you want to use a cache, and for
how long results should be cached (*in plain English*, not milliseconds, because
who really wants to calculate that each time?).

## Installation

```
npm install apicache
```

## Dependencies

None, unless using this with Redis.

## Usage

To use, simply inject the middleware (example: `apicache.middleware('5 minutes', [optionalMiddlewareToggle])`) into your routes.  Everything else is automagic.

#### Cache a route
```js
import express from 'express'
import apicache from 'apicache'

let app = express()
let cache = apicache.middleware

app.get('/api/collection/:id?', cache('5 minutes'), (req, res) => {
  // do some work... this will only occur once per 5 minutes
  res.json({ foo: 'bar' })
})
```

#### Cache all routes
```js
let cache = apicache.middleware

app.use(cache('5 minutes'))

app.get('/will-be-cached', (req, res) => {
  res.json({ success: true })
})
```

#### Use with Redis
```js
import express from 'express'
import apicache from 'apicache'
import redis from 'redis'

let app = express()

// if redisClient option is defined, apicache will use redis client
// instead of built-in memory store
let cacheWithRedis = apicache
                      .options({ redisClient: redis.createClient() })
                      .middleware

app.get('/will-be-cached', cacheWithRedis('5 minutes'), (req, res) => {
  res.json({ success: true })
})
```

#### Cache grouping and manual controls
```js
import apicache from 'apicache'
let cache = apicache.middleware

app.use(cache('5 minutes'))

// routes are aoutmatically added to index, but may be further added
// to groups for quick deleting of collections
app.get('/api/:collection/:item?', (req, res) => {
  req.apicacheGroup = req.params.collection
  res.json({ success: true })
})

// add route to display cache index
app.get('/api/cache/index', (req, res) => {
  res.json(apicache.getIndex())
})

// add route to manually clear target/group
app.get('/api/cache/clear/:target?', (req, res) => {
  res.json(apicache.clear(req.params.target))
})

/*

GET /api/foo/bar --> caches entry at /api/foo/bar and adds a group called 'foo' to index
GET /api/cache/index --> displays index
GET /api/cache/clear/foo --> clears all cached entries for 'foo' group/collection

*/
```

#### Use with middleware toggle for fine control
```js
// higher-order function returns false for requests of other status codes (e.g. 403, 404, 500, etc)
const onlyStatus200 = req => req.statusCode === 200
<commit_msg>Fix typo in readme<commit_after>A simple API response caching middleware for Express/Node using plain-english durations.
=======

[![Build Status via Travis CI](https://travis-ci.org/kwhitley/apicache.svg?branch=master)](https://travis-ci.org/kwhitley/apicache)

## Why?

Because caching of simple data/responses should ALSO be simple.

This day and age, with less and less heavy lifting done on the server,
the most common thing we find ourselves doing is
letting the server power the API.  Whether the data is stored in Mongo, SQL,
CouchDB, or whatever - you get a request, you fetch the data, and you return
the data.  Sometimes these fetches are costly and you want to cache the response
so the next hit doesn't hammer your server.  This is why caching exists.

The problem is, with so many cache options, people are still left to fend for themselves
when it comes to implementation.  It often boils down to a manual process similar to the following:

1. Get the request
2. Check your cache for the key/url.
3. If found, intercept and output the cached version.
4. If not, do the work, cache it, and output.

You're still left wrapping the content of each request with this cache-checking mechanism.

Now it can be as simple as telling the request that you want to use a cache, and for
how long results should be cached (*in plain English*, not milliseconds, because
who really wants to calculate that each time?).

## Installation

```
npm install apicache
```

## Dependencies

None, unless using this with Redis.

## Usage

To use, simply inject the middleware (example: `apicache.middleware('5 minutes', [optionalMiddlewareToggle])`) into your routes.  Everything else is automagic.

#### Cache a route
```js
import express from 'express'
import apicache from 'apicache'

let app = express()
let cache = apicache.middleware

app.get('/api/collection/:id?', cache('5 minutes'), (req, res) => {
  // do some work... this will only occur once per 5 minutes
  res.json({ foo: 'bar' })
})
```

#### Cache all routes
```js
let cache = apicache.middleware

app.use(cache('5 minutes'))

app.get('/will-be-cached', (req, res) => {
  res.json({ success: true })
})
```

#### Use with Redis
```js
import express from 'express'
import apicache from 'apicache'
import redis from 'redis'

let app = express()

// if redisClient option is defined, apicache will use redis client
// instead of built-in memory store
let cacheWithRedis = apicache
                      .options({ redisClient: redis.createClient() })
                      .middleware

app.get('/will-be-cached', cacheWithRedis('5 minutes'), (req, res) => {
  res.json({ success: true })
})
```

#### Cache grouping and manual controls
```js
import apicache from 'apicache'
let cache = apicache.middleware

app.use(cache('5 minutes'))

// routes are automatically added to index, but may be further added
// to groups for quick deleting of collections
app.get('/api/:collection/:item?', (req, res) => {
  req.apicacheGroup = req.params.collection
  res.json({ success: true })
})

// add route to display cache index
app.get('/api/cache/index', (req, res) => {
  res.json(apicache.getIndex())
})

// add route to manually clear target/group
app.get('/api/cache/clear/:target?', (req, res) => {
  res.json(apicache.clear(req.params.target))
})

/*

GET /api/foo/bar --> caches entry at /api/foo/bar and adds a group called 'foo' to index
GET /api/cache/index --> displays index
GET /api/cache/clear/foo --> clears all cached entries for 'foo' group/collection

*/
```

#### Use with middleware toggle for fine control
```js
// higher-order function returns false for requests of other status codes (e.g. 403, 404, 500, etc)
const onlyStatus200 = req => req.statusCode === 200

{'fraction_non_alphanumeric': 0.1174420163560799, 'fraction_numerical': 0.00670331143584931, 'mean_word_length': 3.9078947368421053, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 23, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1607532', 'n_tokens_mistral': 2275, 'n_tokens_neox': 2185, 'n_words': 933}