-
Notifications
You must be signed in to change notification settings - Fork 6
/
encode_decode_handler.erl
56 lines (45 loc) · 1.67 KB
/
encode_decode_handler.erl
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
-module(encode_decode_handler).
-behaviour(sheep_http).
-export([init/2, read/2, sheep_init/2 ]).
-include("sheep.hrl").
-spec init(cowboy_req:req(), term()) -> tuple().
init(Req, Opts) ->
{sheep_http, Req, Opts}.
-spec sheep_init(sheep_request(), term()) -> {sheep_response(), term()}.
sheep_init(_Request, _Opts) ->
Options =
#sheep_options{
decode_spec =
#{
<<"application/json">> =>
fun(Data) ->
M = jiffy:decode(Data, [return_maps]),
M#{custom_encoder => ok}
end
},
encode_spec =
#{
<<"application/json">> =>
fun(Data) ->
jiffy:encode(Data#{custom_decoder => ok})
end
}
},
State = [],
{Options, State}.
-spec read(sheep_request(), term()) -> sheep_response().
read(#sheep_request{bindings = #{<<"kind">> := <<"empty">>}} = _Request, _State) ->
#sheep_response{status_code = 204};
read(#sheep_request{bindings = #{<<"kind">> := <<"empty_404">>}} = _Request, _State) ->
#sheep_response{status_code = 404};
read(#sheep_request{bindings = #{<<"kind">> := <<"undefined">>}} = _Request, _State) ->
#sheep_response{status_code = 204};
read(#sheep_request{bindings = #{<<"kind">> := <<"invalid_payload">>}} = _Request, _State) ->
Body = [answer, 42],
#sheep_response{status_code = 200, body = Body};
read(#sheep_request{body = Body}, _State)->
Body2 = if
is_map(Body) -> Body#{readed => true};
true -> #{readed => true}
end,
#sheep_response{status_code = 200, body = Body2}.