Skip to content

Instantly share code, notes, and snippets.

@bluzky
Created May 18, 2018 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluzky/a1ee3572fc223867735fcbd52263ecc4 to your computer and use it in GitHub Desktop.
Save bluzky/a1ee3572fc223867735fcbd52263ecc4 to your computer and use it in GitHub Desktop.
defmodule PhoenixCache.Plug.Cache doimport Plug.Conn
# 6 minute
@default_ttl 6 * 60
def init(ttl \\ nil), do: ttl
def call(conn, ttl \\ nil) do
ttl = ttl || @default_ttl
# Chỉ cache với GET requestif conn.method == "GET" do# tạo key từ request path và query param, thông thường# thì cùng path và cùng param thì kết quả là giống nhau
key = "#{conn.request_path}-#{conn.query_string}"
case PhoenixCache.Bucket.get(key) do
{:ok, body} ->
IO.puts("PLUG HIT")
# nếu đã cache thì trả về ngay
conn
|> send_resp(200, body)
|> halt
_ ->
IO.puts("PLUG MISS")
# nếu chưa cache thì xử lý như bình thường
conn
|> assign(:ttl, ttl)
|> register_before_send(&cache_before_send/1) # gọi hàm này trước khi trả vềendelse
conn
endend
def cache_before_send(conn) do# nếu request đuợc xử lý thành công thì cacheif conn.status == 200 dokey = "#{conn.request_path}-#{conn.query_string}"data = conn.resp_body
PhoenixCache.Bucket.set(key, data, conn.assigns[:ttl] || @default_ttl)
conn
else# không thì kệ chúng mày
conn
endend
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment