icyleaf / halite

💎HTTP Requests Client with a chainable REST API, built-in sessions and middlewares.
MIT License
170 stars 13 forks source link

feature: local cache #24

Closed icyleaf closed 6 years ago

icyleaf commented 6 years ago

Better to debug and improve the speed for developing third party API.

Logic

Cache key

generate algorithm md5(verb + url + body)

Cache response

Store response into two files:

metadata JSON structure:

{
  "status_code": 200,
  "headers": {
    "content-type": "application/json",
  },
}

Expires time

Supports Int32, Time::Span is enough.

Examples

Use it with single call

Halite.cache.get "https://httpbin.ogr/get"
Halite.cache(directory: "cache", expired: 1.hour).get "https://httpbin.ogr/get"

# Loads the content of "cache/get.txt" 
Halite.cache(file: "get.txt").get "https://httpbin.ogr/get"

Use it with instance client:

client = Halite::Client.new do |options|
  options.cache = true
end

client = Halite::Client.new do |options|
  options.cache(directory: "cache", expired: 1.hour)
end

client.get "https://httpbin.ogr/get"

This request will store into cache path: "cache/{cache_key}" with two files:

metadata.json:

{
  "status_code": 200,
  "headers": {
    "content-type": "application/json",
  },
}

{cache_key}.cache

{"args":{"name":"foobar"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"Halite/0.3.2"},"origin":"60.206.194.34","url":"http://httpbin.org/get?name=foobar"}

Load from file

It supports load cache from file, just passes file argument, Cache will load the content of file and return to Halite::Response no matter request whatever is.

PR

35

icyleaf commented 6 years ago

29

icyleaf commented 6 years ago

My gosh, this feature make me commited a lot to prepare.

icyleaf commented 6 years ago

Finally, It had been done.