-
Notifications
You must be signed in to change notification settings - Fork 600
Expand file tree
/
Copy pathmethod_override.ex
More file actions
69 lines (51 loc) · 2.05 KB
/
method_override.ex
File metadata and controls
69 lines (51 loc) · 2.05 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
defmodule Plug.MethodOverride do
@moduledoc """
This plug overrides the request's `POST` method with the method defined in
the `_method` request parameter.
The `POST` method can be overridden only by these HTTP methods:
* `PUT`
* `PATCH`
* `DELETE`
This plug only replaces the request method if the `_method` request
parameter is a string. If the `_method` request parameter is not a string,
the request method is not changed.
> #### Parse Body Parameters First {: .info}
>
> This plug expects the body parameters to be **already fetched and
> parsed**. Those can be fetched with `Plug.Parsers`.
This plug doesn't accept any options.
To recap, here are all the conditions that the request must meet in order
for this plug to replace the `:method` field in the `Plug.Conn`:
1. The conn's request `:method` must be `POST`.
1. The conn's `:body_params` must have been fetched already (for example,
with `Plug.Parsers`).
1. The conn's `:body_params` must have a `_method` field that is a string
and whose value is `"PUT"`, `"PATCH"`, or `"DELETE"` (case insensitive).
## Usage
# You'll need to fetch and parse parameters first, for example:
# plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json]
plug Plug.MethodOverride
"""
@behaviour Plug
@allowed_methods ~w(DELETE PUT PATCH)
@impl true
def init([]), do: []
@impl true
def call(%Plug.Conn{method: "POST", body_params: body_params} = conn, []),
do: override_method(conn, body_params)
def call(%Plug.Conn{} = conn, []), do: conn
defp override_method(conn, %Plug.Conn.Unfetched{}) do
# Just skip it because maybe it is a content-type that
# we could not parse as parameters (for example, text/gps)
conn
end
defp override_method(%Plug.Conn{} = conn, body_params) do
with method when is_binary(method) <- body_params["_method"] || "",
method = String.upcase(method, :ascii),
true <- method in @allowed_methods do
%{conn | method: method}
else
_ -> conn
end
end
end