Skip to content

Commit 6f3df02

Browse files
committed
Req: Add new/2
1 parent ef85529 commit 6f3df02

2 files changed

Lines changed: 18 additions & 24 deletions

File tree

lib/req.ex

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -506,47 +506,41 @@ defmodule Req do
506506
iex> URI.to_string(req.url)
507507
"https://elixir-lang.org"
508508
509-
Fake adapter:
509+
With a url and options:
510510
511-
iex> fake = fn request ->
512-
...> {request, Req.Response.new(status: 200, body: "it works!")}
513-
...> end
514-
iex>
515-
iex> req = Req.new(adapter: fake)
516-
iex> Req.get!(req).body
517-
"it works!"
511+
iex> req = Req.new("https://elixir-lang.org", method: :head)
512+
iex> req.method
513+
:head
518514
519515
"""
520-
@spec new(options :: keyword()) :: Req.Request.t()
521-
def new(options \\ []) do
522-
options = Keyword.merge(default_options(), options)
516+
@spec new(request :: url() | keyword() | Req.Request.t(), options :: keyword()) :: Req.Request.t()
517+
def new(request \\ [], options \\ [])
518+
519+
def new(options1, options2) when is_list(options1) and is_list(options2) do
520+
options = Keyword.merge(default_options(), options1 ++ options2)
523521
{plugins, options} = Keyword.pop(options, :plugins, [])
524522

525523
@req
526524
|> run_plugins(plugins)
527525
|> merge(options)
528526
end
529527

530-
defp new(%Req.Request{} = request, options) when is_list(options) do
531-
Req.merge(request, options)
532-
end
533-
534-
defp new(options1, options2) when is_list(options1) and is_list(options2) do
535-
new(options1 ++ options2)
528+
def new(url, options) when (is_binary(url) or is_struct(url, URI)) and is_list(options) do
529+
new([url: url] ++ options)
536530
end
537531

538-
defp new(url, options) when (is_binary(url) or is_struct(url, URI)) and is_list(options) do
539-
new([url: url] ++ options)
532+
def new(%Req.Request{} = request, options) when is_list(options) do
533+
Req.merge(request, options)
540534
end
541535

542-
defp new(request, options) when is_list(options) do
536+
def new(request, options) when is_list(options) do
543537
raise ArgumentError,
544-
"expected 1st argument to be a request, got: #{inspect(request)}"
538+
"expected 1st argument to be a url, a keyword list, or a request, got: #{inspect(request)}"
545539
end
546540

547-
defp new(_request, options) do
541+
def new(_request, options) do
548542
raise ArgumentError,
549-
"expected 2nd argument to be an options keywords list, got: #{inspect(options)}"
543+
"expected 2nd argument to be a keyword list, got: #{inspect(options)}"
550544
end
551545

552546
@doc false

test/req_test.exs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ defmodule ReqTest do
44
doctest Req,
55
only:
66
[
7-
new: 1,
7+
new: 2,
88
merge: 2,
99
get_headers_list: 1,
1010
assign: 2,

0 commit comments

Comments
 (0)