Repository navigation
Expand file tree
/
Copy pathgithub_resultstream.ex
More file actions
77 lines (63 loc) · 1.56 KB
/
Copy pathgithub_resultstream.ex
File metadata and controls
77 lines (63 loc) · 1.56 KB
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
defmodule HelloWeb.Gateway do
use HTTPoison.Base
@endpoint "https://api.github.com/search/repositories"
def endpoint do
@endpoint
end
defp process_url(url) do
@endpoint <> url
end
defp process_request_headers(headers) do
headers ++ [
{"Authorization", "Basic #{:base64.encode(credentials)}"}
]
end
defp credentials do
"#{config[:access_token]}:x-oauth-basic"
end
defp config do
# Application.get_env(:my_app, __MODULE__)
end
end
defmodule HelloWeb.ResultStream do
alias HelloWeb.Gateway
def new(url) do
fetch_page(url)
# Stream.resource(
# fn -> fetch_page(url) end,
# &process_page/1,
# fn _ -> end
# )
end
defp fetch_page(url) do
response = Gateway.get!(url)
items = Poison.decode!(response.body)
links = parse_links(List.keyfind(response.headers, "Link", 0))
{items, links}
# {items, links["next"]}
end
def parse_links(nil) do
%{}
end
def parse_links(links_string) do
{"Link", tuple} = links_string
links = String.split(tuple, ", ")
Enum.map(links, fn link ->
[_,name] = Regex.run(~r{rel="([a-z]+)"}, link)
[_,url] = Regex.run(~r{<([^>]+)>}, link)
short_url = String.replace(url, Gateway.endpoint, "")
{name, short_url}
end) |> Enum.into(%{})
end
defp process_page({nil, nil}) do
{:halt, nil}
end
defp process_page({nil, next_page_url}) do
next_page_url
|> fetch_page
|> process_page
end
defp process_page({items, next_page_url}) do
{items["items"], {nil, next_page_url}}
end
end