Skip to content

Instantly share code, notes, and snippets.

@dvinciguerra
Last active June 8, 2021 01:03
Show Gist options
  • Save dvinciguerra/9d26f7ff8fcd0bbacf9d325748dc783a to your computer and use it in GitHub Desktop.
Save dvinciguerra/9d26f7ff8fcd0bbacf9d325748dc783a to your computer and use it in GitHub Desktop.
Epic Games - Ruby script to fetch free games from website
require 'json'
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'faraday'
end
DEFAULT_API_URL = 'https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=pt-BR&country=BR&allowCountries=BR'
EPIC_GAMES_FREE_GAMES_API_URL = ENV['EPIC_GAMES_API_URL'] || DEFAULT_API_URL
class Game < Struct.new(:id, :title, :image, :slug, :started_at, :ended_at, keyword_init: true)
def to_json
{
id: id,
title: title,
image: image,
slug: slug,
started_at: started_at,
ended_at: ended_at,
}
end
end
response = Faraday.get(EPIC_GAMES_FREE_GAMES_API_URL)
raise RuntimeError.new("Error connecting to the Epic Games free-games API!") unless response.success?
payload = JSON.parse(response.body)
select_games = ->(payload) {
payload.dig('data', 'Catalog', 'searchStore', 'elements')
}
select_image = ->(game_payload) {
image = game_payload['keyImages'].find { |image| image['type'] == 'VaultClosed' }
image ? image['url'] : nil
}
select_promotion_dates = ->(game_payload) {
offers = game_payload['promotions']['promotionalOffers'].first
offers ? offers['promotionalOffers'].first : { 'startDate' => nil, 'endDate' => nil }
}
select_promotion_started_date = ->(game_payload) {
select_promotion_dates.(game_payload)['startDate']
}
select_promotion_end_date = ->(game_payload) {
select_promotion_dates.(game_payload)['endDate']
}
games = select_games.(payload).map do |game|
Game.new(
id: game['id'],
title: game['title'],
image: select_image.(game),
slug: game['urlSlug'],
started_at: select_promotion_started_date.(game),
ended_at: select_promotion_end_date.(game),
)
end
pp games
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment