Add FeedUpdater
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
defmodule ElixirRss.CLI do
|
||||
|
||||
require Logger
|
||||
|
||||
@default_host "0.0.0.0"
|
||||
@default_port 8080
|
||||
@default_basepath "/"
|
||||
|
||||
def run(argv) do
|
||||
def main(argv) do
|
||||
parse_args(argv)
|
||||
|> process()
|
||||
end
|
||||
@@ -38,6 +41,6 @@ defmodule ElixirRss.CLI do
|
||||
end
|
||||
|
||||
defp process({host, port, path}) do
|
||||
IO.puts("Host: #{host}, Port: #{port}, Basepath: #{path}")
|
||||
Logger.info("Host: #{host}, Port: #{port}, Basepath: #{path}")
|
||||
end
|
||||
end
|
||||
|
||||
33
lib/elixir_rss/feed_updater.ex
Normal file
33
lib/elixir_rss/feed_updater.ex
Normal file
@@ -0,0 +1,33 @@
|
||||
defmodule ElixirRss.FeedUpdater do
|
||||
use GenServer
|
||||
|
||||
def start_link(opts) do
|
||||
GenServer.start_link(__MODULE__, %{}, opts)
|
||||
end
|
||||
|
||||
def get_state(server, url) do
|
||||
GenServer.call(server, {:get, url})
|
||||
end
|
||||
|
||||
def update(server, url) do
|
||||
GenServer.call(server, {:update, url})
|
||||
end
|
||||
|
||||
|
||||
@impl true
|
||||
def init(state) do
|
||||
{:ok, state}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_call({:get, url}, _from, state) do
|
||||
{:reply, Map.get(state, url), state}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_call({:update, url}, _from, state) do
|
||||
new_model = ElixirRss.Fetcher.fetch_model(url)
|
||||
new_state = Map.put(state, url, new_model)
|
||||
{:reply, :ok, new_state}
|
||||
end
|
||||
end
|
||||
31
lib/elixir_rss/fetcher.ex
Normal file
31
lib/elixir_rss/fetcher.ex
Normal file
@@ -0,0 +1,31 @@
|
||||
defmodule ElixirRss.Fetcher do
|
||||
def fetch_model(url) do
|
||||
url
|
||||
|> fetch()
|
||||
|> elem(1)
|
||||
|> parse_rss_to_model()
|
||||
end
|
||||
|
||||
def fetch(url) do
|
||||
url
|
||||
|> HTTPoison.get()
|
||||
|> handle_response()
|
||||
end
|
||||
|
||||
defp handle_response({:ok, %{status_code: 200, body: body}}) do
|
||||
{:ok, body}
|
||||
end
|
||||
defp handle_response({_, %{status_code: _, body: body}}) do
|
||||
{:error, body}
|
||||
end
|
||||
|
||||
def parse_rss_to_model(rss_xml) do
|
||||
rss_xml
|
||||
|> FastRSS.parse_rss()
|
||||
|> elem(1)
|
||||
|> Map.get("items")
|
||||
|> Enum.map(fn item ->
|
||||
Map.take(item, ["title", "description"])
|
||||
end)
|
||||
end
|
||||
end
|
||||
@@ -1,14 +0,0 @@
|
||||
defmodule ElixirRss.Http do
|
||||
def fetch(url) do
|
||||
url
|
||||
|> HTTPoison.get()
|
||||
|> handle_response()
|
||||
end
|
||||
|
||||
defp handle_response({:ok, %{status_code: 200, body: body}}) do
|
||||
{:ok, body}
|
||||
end
|
||||
defp handle_response({_, %{status_code: _, body: body}}) do
|
||||
{:error, body}
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user