Nothing has been indexed for 0.12.1 yet. The tag is recorded, its shard.yml has not been read, so the manifest and dependency list below are empty because they are unknown rather than because they are absent.

Installation

# Add this to your shard.yml
dependencies:
  cache:
    github: crystal-cache/cache
    version: ~> 0.12.1

Then run:

shards install

shard.yml

No shard.yml has been indexed for 0.12.1. You can read it on the repository.

Dependencies

Unknown: the shard.yml for this version has not been read yet.

README

This README is the one indexed from the repository at its latest ref, not from the tag for this version.

# Caché

![Crystal CI](https://github.com/crystal-cache/cache/workflows/Crystal%20CI/badge.svg)
[![GitHub release](https://img.shields.io/github/release/crystal-cache/cache.svg)](https://github.com/crystal-cache/cache/releases)
[![License](https://img.shields.io/github/license/crystal-cache/cache.svg)](https://github.com/crystal-cache/cache/blob/main/LICENSE)

A key/value store where pairs can expire after a specified interval. Keys are always strings, and values can be any serializable Crystal type.

## Installation

Add this to your application's `shard.yml`:

```yaml
dependencies:
  cache:
    github: crystal-cache/cache
```

## Example

Caching means to store content generated during the request-response cycle
and to reuse it when responding to similar requests.

The first time the result is returned from the query it is stored in the query cache (in memory),
and the second time it is pulled from memory.

Memory cache can store any serializable Crystal object.

The next example shows how to get a single GitHub user and cache the result in memory.

```crystal
require "http/client"
require "json"
require "cache"

cache = Cache::MemoryStore(String).new(expires_in: 30.minutes)
github_client = HTTP::Client.new(URI.parse("https://api.github.com"))

# Define how an object is mapped to JSON.
class User
  include JSON::Serializable

  property login : String
  property id : Int32
end

username = "crystal-lang"

# First request.
# Getting data from GitHub and writing it to cache.
user_json = cache.fetch("user_#{username}") do
  response = github_client.get("/users/#{username}")
  User.from_json(response.body).to_json
end

user = User.from_json(user_json)
user.id # => 6539796

# Second request.
# Getting data from cache.
user_json = cache.fetch("user_#{username}") do
  response = github_client.get("/users/#{username}")
  User.from_json(response.body).to_json
end

user = User.from_json(user_json)
user.id # => 6539796
```

## Usage

> **Note**: The cache API has been updated in version 1.0.0. Keys are now always strings, and the store interface uses a single type parameter `Store(V)` where `V` is the value type. The previous `Store(K, V)` interface has been removed.

### Available stores

* [x] Null store
* [x] Memory
* [x] Filesystem

There are multiple cache store implementations,
each having its own additional features. See the classes
under the `/src/cache/stores` directory, e.g.

### Third-party store implementations

* [redis_cache_store](https://github.com/crystal-cache/redis_cache_store)
* [redis_legacy_cache_store](https://github.com/crystal-cache/redis_legacy_cache_store)
* [mem_cache_store](https://github.com/crystal-cache/mem_cache_store)
* [postgres_cache_store](https://github.com/crystal-cache/postgres_cache_store)
* [mysql_cache_store](https://github.com/crystal-cache/mysql_cache_store)

### Commands

All store implementations support:

* `fetch` - Fetch data with fallback block
* `write` - Write data to cache
* `read` - Read data from cache
* `delete` - Delete a specific key
* `exists?` - Check if key exists
* `clear` - Clear all cache entries
* `increment` - Increment an integer value
* `decrement` - Decrement an integer value

#### Return values

The shared store methods return:

* `fetch` returns the cached value, or the block value after writing it.
* `write` returns the written value.
* `read` returns the cached value, or `nil` for a missing or expired key.
* `delete` returns `true` when an entry is deleted, `false` when the key does not exist.
* `exists?` returns `true` when a non-expired entry exists, `false` otherwise.
* `increment` and `decrement` return the updated integer value, or `nil` when the key is missing or the cached value is not an integer.
* `clear` removes entries; its return value should not be used.

#### fetch

Fetches data from the cache, using the given `key` (which must be a string). If there is data in the cache
with the given `key`, then that data is returned.

If there is no such data in the cache, then a `block` will be passed the `key`
and executed in the event of a cache miss.

Setting `:expires_in` will set an expiration time on the cache.
All caches support auto-expiring content after a specified number of seconds.
This value can be specified as an option to the constructor (in which case all entries will be affected),
or it can be supplied to the `fetch` or `write` method to affect just one entry.

```crystal
store = Cache::MemoryStore(String).new(expires_in: 1.hour)

# Basic usage with block
value = store.fetch("key") do
  "default_value"
end

# With custom expiration for this specific entry
value = store.fetch("key", expires_in: 10.minutes) do
  "value_with_custom_expiry"
end
```

#### write

Writes the `value` to the cache, with the `key` (which must be a string).

Optional `expires_in` will set an expiration time on the `key`.

> Options are passed to the underlying cache implementation.

```crystal
store = Cache::MemoryStore(String).new(12.hours)

# Basic write
store.write("foo", "bar")

# With custom expiration
store.write("temp_data", "value", expires_in: 5.minutes)
```

#### read

Reads data from the cache, using the given `key` (which must be a string).

If there is data in the cache with the given `key`, then that data is returned.
Otherwise, `nil` is returned.

```crystal
store = Cache::MemoryStore(String).new(12.hours)
store.write("foo", "bar")

store.read("foo") # => "bar"
```

#### delete

Deletes an entry in the cache using the given `key` (which must be a string). Returns `true` if an entry is deleted, `false` if the key didn't exist.

> Options are passed to the underlying cache implementation.

```crystal
store = Cache::MemoryStore(String).new(12.hours)

store.write("foo", "bar")
store.read("foo") # => "bar"

store.delete("foo") # => true
store.read("foo") # => nil

# Deleting non-existent key
store.delete("nonexistent") # => false
```

#### clear

Deletes all items from the cache. This operation is irreversible and will remove all cached data.

> Options are passed to the underlying cache implementation.

```crystal
store = Cache::MemoryStore(String).new(12.hours)

store.write("foo", "bar")
store.write("baz", "qux")
store.keys.size # => 2

store.clear
store.keys.size # => 0
store.read("foo") # => nil
store.read("baz") # => nil
```

#### exists?

Checks if a key exists in the cache. Returns `true` if the key exists and has not expired, `false` otherwise.

```crystal
store = Cache::MemoryStore(String).new(12.hours)

store.write("foo", "bar")
store.exists?("foo") # => true
store.exists?("baz") # => false

store.delete("foo")
store.exists?("foo") # => false
```

#### increment and decrement

Updates an integer value in the cache. If the key is missing or the value is not an integer, the operation returns `nil`.

```crystal
store = Cache::MemoryStore(Int32).new(12.hours)

store.write("count", 1)
store.increment("count") # => 2
store.decrement("count") # => 1
store.increment("missing") # => nil
```

### Memory

A cache store implementation which stores everything into memory in the
same process.

Can store any serializable Crystal object.

```crystal
cache = Cache::MemoryStore(Hash(String, String | Int32)).new(expires_in: 1.minute)
cache.fetch("data_key") do
  {"name" => "John", "age" => 18}
end
```

Cached data for `MemoryStore(String)` are compressed by default.
To turn off compression, pass `compress: false` to the initializer.

For other value types, the `compress` option is ignored.

```crystal
cache = Cache::MemoryStore(String).new(expires_in: 1.minute, compress: false)
cache.fetch("today") do
  Time.utc.day_of_week.to_s
end
```

### Filesystem

A cache store implementation which stores everything on the filesystem.

```crystal
cache_path = "#{__DIR__}/cache"

cache = Cache::FileStore(String).new(expires_in: 12.hours, cache_path: cache_path)

cache.fetch("today") do
  Time.utc.day_of_week.to_s
end
```

Cached data for `FileStore(String)` are not compressed by default.
To enable compression, pass `compress: true` to the initializer.

For other value types, the `compress` option is ignored.

```crystal
cache = Cache::FileStore(String).new(expires_in: 12.hours, cache_path: cache_path, compress: true)
cache.fetch("today") do
  Time.utc.day_of_week.to_s
end
```

### Null store

A cache store implementation which doesn't actually store anything. Useful in
development and test environments where you don't want caching turned on but
need to go through the caching interface.

`NullStore#read` always returns `nil`, `NullStore#exists?` always returns `false`, and `NullStore#delete` returns `false`.

```crystal
cache = Cache::NullStore(String).new(expires_in: 1.minute)
cache.fetch("today") do
  Time.utc.day_of_week.to_s
end
```

## Logging

To enable logging, set the log level to `:debug`:

```crystal
Log.builder.bind "cache.*", :debug, Log::IOBackend.new
```

## Contributing

1. Fork it (<https://github.com/crystal-cache/cache/fork>)
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

## Contributors

* [mamantoha](https://github.com/mamantoha) Anton Maminov - creator, maintainer