diff --git a/src/providers/7tv.cr b/src/providers/7tv.cr index a26608a..6cf2a16 100644 --- a/src/providers/7tv.cr +++ b/src/providers/7tv.cr @@ -9,8 +9,8 @@ module Providers::SevenTV def get_user_cosmetics(user_id : String) stored_used_id = SQL.query_one? "SELECT twitch_id FROM seventv_ids WHERE twitch_id = ? LIMIT 1;", user_id, as: String if user_id != stored_used_id - seventv_user_id = get_seventv_user_id(user_id)["user"]["id"].to_s - SQL.exec "INSERT OR IGNORE INTO seventv_ids (twitch_id, seventv_id) VALUES (?, ?)", user_id, seventv_user_id + stv_id = get_seventv_user_id(user_id)["user"]["id"].to_s + SQL.exec "INSERT OR IGNORE INTO seventv_ids (twitch_id, seventv_id) VALUES (?, ?)", user_id, stv_id else stv_id = SQL.query_one "SELECT seventv_id FROM seventv_ids WHERE twitch_id = ?", user_id, as: String end diff --git a/src/utils.cr b/src/utils.cr index 0f9d2f4..b54e2a7 100644 --- a/src/utils.cr +++ b/src/utils.cr @@ -15,3 +15,22 @@ module Utils end end end + +module Utils::Redis + extend self + + def getExpireTime(key) + REDIS_DB.ttl(key) + end + + def retrieveFromCache(keyName) + if keyName && (json = REDIS_DB.get("#{Kemal.config.app_name}:#{keyName}")) + return json + end + end + + def save(keyName, json_data : String, expiration = 60) + REDIS_DB.set("#{Kemal.config.app_name}:#{keyName}", json_data, ex: expiration) + end +end + diff --git a/src/vanity-tester-backend.cr b/src/vanity-tester-backend.cr index ac97e60..b17d547 100644 --- a/src/vanity-tester-backend.cr +++ b/src/vanity-tester-backend.cr @@ -15,23 +15,43 @@ Kemal.config.port = CONFIG.port Kemal.config.shutdown_message = false Kemal.config.app_name = "vanity-tester-backend" SQL = DB.open("sqlite3://#{CONFIG.db}") -REDIS_DB = Redis::Client.new(CONFIG.redisUrl) +REDIS_DB = Redis::Client.new(URI.parse("redis://#{CONFIG.redisUrl}")) LOGGER = LogHandler.new(STDOUT, CONFIG.log_level) Utils.create_db HEADERS = HTTP::Headers{"User-Agent" => "Vanity-Tester-Backend/0.1.0"} +before_get do |env| + # Every response is a JSON + env.response.content_type = "application/json" +end + get "/badges" do |env| - Handlers.parse_badges(env) + if data = Utils::Redis.retrieveFromCache("badges") + next data + end + data = Handlers.parse_badges(env) + Utils::Redis.save("badges", data, 300) + data end get "/7tv/badges" do |env| - Handlers.parse_7tv_badges(env) + if data = Utils::Redis.retrieveFromCache("7tvbadges") + next data + end + data = Handlers.parse_7tv_badges(env) + Utils::Redis.save("7tvbadges", data, 300) + data end get "/7tv/paints" do |env| - Handlers.parse_7tv_paints(env) + if data = Utils::Redis.retrieveFromCache("7tvpaints") + next data + end + data = Handlers.parse_7tv_paints(env) + Utils::Redis.save("7tvpaints", data, 300) + data end get "/7tv/cosmetics/:user" do |env|