Skip to content

Commit

Permalink
Add Req.Request.new/1 and Req.Request.request/1
Browse files Browse the repository at this point in the history
Closes #197
Closes #130
  • Loading branch information
wojtekmach committed Jul 10, 2023
1 parent 167f513 commit df06a29
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions lib/req/request.ex
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,39 @@ defmodule Req.Request do
registered_options: MapSet.new(),
current_request_steps: []

@doc """
Returns a new request struct.
## Options
* `:method` - the request method, defaults to `:get`.
* `:url` - the request URL.
* `:headers` - the request headers, defaults to `[]`.
* `:body` - the request body, defaults to `nil`.
* `:adapter` - the request adapter, defaults to calling [`run_finch`](`Req.Steps.run_finch/1`).
## Examples
iex> req = Req.Request.new(url: "https://httpbin.org/status/201")
iex> {:ok, request, response} = Req.Request.request(req)
iex> request.url.host
"httpbin.org"
iex> response.status
201
"""
def new(options) do
options =
options
|> Keyword.validate!([:method, :url, :headers, :body, :adapter])
|> Keyword.update(:url, URI.new!(""), &URI.new!/1)

struct!(__MODULE__, options)
end

@doc """
Gets the value for a specific private `key`.
"""
Expand Down Expand Up @@ -667,6 +700,31 @@ defmodule Req.Request do
end
end

@doc """
Runs the requet pipeline.
Returns `{:ok, request, response}` or `{:error, request, exception}`.
## Examples
iex> req = Req.Request.new(url: "https://httpbin.org/status/201")
iex> {:ok, request, response} = Req.Request.request(req)
iex> request.url.host
"httpbin.org"
iex> response.status
201
"""
def request(request) do
case run_request(request) do
{request, %Req.Response{} = response} ->
{:ok, request, response}

{request, exception} ->
{:error, request, exception}
end
end

@doc """
Runs the request pipeline.
Expand Down

0 comments on commit df06a29

Please sign in to comment.