mirror of
https://github.com/mitchell/shortnr.git
synced 2025-12-19 14:07:22 +00:00
Add Endpoints behaviour and refactor router and related methods
This commit is contained in:
parent
1502d10cdc
commit
98684feb2d
8 changed files with 98 additions and 62 deletions
|
|
@ -64,3 +64,12 @@ defmodule Shortnr.Transport.HTTP do
|
|||
defp status_to_code(:not_found), do: 404
|
||||
defp status_to_code(:internal_server_error), do: 500
|
||||
end
|
||||
|
||||
defmodule Shortnr.Transport.HTTP.Endpoints do
|
||||
@moduledoc """
|
||||
This modules is a behaviour that should be implemented by each service that needs to be routed by
|
||||
Plug.Router
|
||||
"""
|
||||
|
||||
@callback select(Plug.Conn.t(), atom, term) :: Plug.Conn.t()
|
||||
end
|
||||
|
|
|
|||
|
|
@ -3,28 +3,29 @@ defmodule Shortnr.Transport.Text do
|
|||
This modules contains functions to decode and encode text formatted http requests and responses.
|
||||
"""
|
||||
|
||||
import Plug.Conn
|
||||
alias Shortnr.Transport.HTTP
|
||||
alias Shortnr.Transport.Text.Encodable
|
||||
|
||||
@spec decode_request(Plug.Conn.t()) :: HTTP.ok_error()
|
||||
def decode_request(conn) do
|
||||
import Plug.Conn
|
||||
|
||||
@spec decode(HTTP.ok_error()) :: HTTP.ok_error()
|
||||
def decode({:ok, _body, conn}) do
|
||||
{:ok, body, conn} = read_body(conn)
|
||||
{:ok, body, conn}
|
||||
end
|
||||
|
||||
@spec encode_response(HTTP.ok_error()) :: HTTP.ok_error()
|
||||
def encode_response(ok_error = {:error, _, _}), do: ok_error
|
||||
@spec encode(HTTP.ok_error()) :: HTTP.ok_error()
|
||||
def encode(ok_error = {:error, _, _}), do: ok_error
|
||||
|
||||
def encode_response({:ok, [], conn}) do
|
||||
def encode({:ok, [], conn}) do
|
||||
{:ok, "", conn}
|
||||
end
|
||||
|
||||
def encode_response({:ok, body, conn}) when is_list(body) do
|
||||
def encode({:ok, body, conn}) when is_list(body) do
|
||||
{:ok, for(item <- body, into: "", do: "#{item}\n"), conn}
|
||||
end
|
||||
|
||||
def encode_response({:ok, body, conn}) do
|
||||
def encode({:ok, body, conn}) do
|
||||
{:ok, Encodable.encode(body), conn}
|
||||
end
|
||||
end
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue