-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
80 lines (60 loc) · 1.75 KB
/
app.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
require "bundler"
require "sinatra"
require "redis"
require "nokogiri"
require "httpclient"
BASE_URL = "https://octodex.github.com/"
if ENV["REDISTOGO_URL"]
uri = URI.parse(ENV["REDISTOGO_URL"])
REDIS = Redis.new(host: uri.host, port: uri.port, password: uri.password)
else
REDIS = Redis.new
end
configure do
enable :cross_origin
set :protection, except: [:json_csrf]
end
before do
response.headers["Access-Control-Allow-Origin"] = "*"
end
options "*" do
response.headers["Allow"] = "GET, POST, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type, Accept, X-User-Email, X-Auth-Token"
response.headers["Access-Control-Allow-Origin"] = "*"
200
end
get "/" do
client = HTTPClient.new
etag = client.head(BASE_URL).headers["ETag"]
cached = REDIS.get(etag)
status = "cached"
if cached && !params["live"]
data = JSON.parse(cached)
else
status = "live"
doc = Nokogiri::HTML(client.get(BASE_URL).body)
items = doc.css(".post").map do |item|
number = item.css("span.pr-1.text-gray").text().gsub("#", "").to_i
name = item.css("a.link-gray-dark").text().gsub(/[\n ]/, "")
image = "#{BASE_URL}#{item.css("img.d-block.width-fit.height-auto.rounded-1")[0]["data-src"]}"
link = "#{BASE_URL}#{item.css("a.link-gray-dark")[0]["href"]}"
authors = item.css(".flex-nowrap a").map do |author|
{
link: author["href"],
image: author.css("img")[0]["src"],
}
end
data = {
number: number,
name: name,
image: image,
link: link,
authors: authors,
}
end
data = items
REDIS.set(etag, data.to_json)
end
content_type "application/json"
{status: status, data: data}.to_json
end