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
70
71
|
-module(dreki_web).
-export([reply/5, reply_json/3, reply_json/4, temporary_redirect/2, req_param/2, identity_name/1]).
-export([content_types_accepted/2, content_types_provided/2]).
-export([detect_web_mimetype/1]).
identity_name(#{identity := Identity}) ->
identity_name(Identity);
identity_name(#{<<"identity">> := Identity}) ->
identity_name(Identity);
identity_name(#{<<"traits">> := #{<<"name">> := #{<<"first">> := F, <<"last">> := L}}}) when is_binary(F), is_binary(L) ->
[F, " ", L];
identity_name(#{<<"traits">> := #{<<"name">> := N}}) when is_binary(N) ->
N;
identity_name(#{<<"traits">> := #{<<"username">> := U}}) when is_binary(U) ->
U;
identity_name(#{<<"traits">> := #{<<"email">> := E}}) when is_binary(E) ->
E;
identity_name(#{<<"id">> := Id}) ->
Id.
reply(Req, Code, Json, Headers, json) ->
reply_json(Req, Code, Json, Headers);
reply(Req, Code, Json, Headers, yaml) ->
reply_yaml(Req, Code, Json, Headers).
reply_json(Req, Code, Json) ->
reply_json(Req, Code, Json, #{}).
reply_json(Req, Code, Json, Headers0) when is_binary(Json) ->
Headers = maps:put(<<"content-type">>, <<"application/json">>, Headers0),
cowboy_req:reply(Code, Headers, Json, Req);
reply_json(Req, Code, Json, Headers0) ->
reply_json(Req, Code, jsone:encode(Json), Headers0).
reply_yaml(Req, Code, Yaml) ->
reply_yaml(Req, Code, Yaml, #{}).
reply_yaml(Req, Code, Yaml, Headers0) when is_binary(Yaml) ->
Headers = maps:put(<<"content-type">>, <<"application/yaml">>, Headers0),
cowboy_req:reply(Code, Headers, Yaml, Req);
reply_yaml(Req, Code, Yaml, Headers0) ->
reply_yaml(Req, Code, fast_yaml:encode(Yaml), Headers0).
temporary_redirect(Req0, Url) ->
cowboy_req:reply(307, #{<<"location">> => Url}, Req0).
req_param(Req, Param) ->
Qs = cowboy_req:parse_qs(Req),
case lists:keyfind(Param, 1, Qs) of
{_, Value} ->
{ok, Value};
_ ->
{error, {missing_param, Param}}
end.
content_types_accepted(Req, State) ->
{[
{{ <<"application">>, <<"json">>, '*'}, from_json},
{{ <<"application">>, <<"yaml">>, '*'}, from_yaml},
{{ <<"multipart">>, <<"form-data">>, '*'}, from_form}
], Req, State}.
content_types_provided(Req, State) ->
{[{{ <<"application">>, <<"json">>, '*'}, to_json}], Req, State}.
detect_web_mimetype(Path) when is_binary(Path) ->
detect_web_mimetype(lists:reverse(binary_to_list(Path)), Path).
detect_web_mimetype([$m, $s, $a, $w, $. | _], _) ->
{<<"application">>, <<"wasm">>, []};
detect_web_mimetype(P, Path) ->
cow_mimetypes:web(Path).
|