aboutsummaryrefslogtreecommitdiff
path: root/apps/dreki/src/tasks/dreki_task.erl
blob: b762aeaf185a53fb20e4d95f2dee7a61f91e6b1b (plain) (blame)
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
-module(dreki_task).

-include("dreki.hrl").

-type new_params() :: #{handler := dreki_task_handler(),
                        id => dreki_id(),
                        description => binary(),
                        params => #{}}.

-export([new/1, validate/1, to_map/1]).
-export([id/1, description/1, handler/1, params/1]).
-export([description/2, handler/2, params/2]).

-spec new(new_params()) -> {ok, dreki_task()} | {error, Reason::term()}.
new(Map) ->
  Id = maps:get(id, Map, dreki_id:get()),
  Description = maps:get(description, Map, undefined),
  Params = maps:get(params, Map, #{}),
  Handler = maps:get(handler, Map, undefined),
  Task = #dreki_task{id=Id, handler=Handler, params=Params, description=Description,
                     persisted=false, dirty=true},
  validate(Task).

-spec validate(dreki_task()) -> {ok, dreki_task()} | {error, Reason::term()}.
validate(#dreki_task{handler = undefined}) ->
  {error, {required, handler}};
validate(Task = #dreki_task{id = Id, handler = _Handler}) ->
  case dreki_id:valid(Id) of
    {error, Err} -> {error, Err};
    ok -> {ok, Task}
  end.

id(Task = #dreki_task{}) ->
  Task#dreki_task.id.

description(Task = #dreki_task{}) ->
  Task#dreki_task.description.

handler(Task = #dreki_task{}) ->
  Task#dreki_task.handler.

params(Task = #dreki_task{}) ->
  Task#dreki_task.params.

handler(Task = #dreki_task{}, NewHandler) ->
  Task#dreki_task{handler=NewHandler, dirty=true}.

description(Task = #dreki_task{}, NewDescription) ->
  Task#dreki_task{description=NewDescription, dirty=true}.

params(Task = #dreki_task{}, NewParams) ->
  Task#dreki_task{params=NewParams, dirty=true}.

to_map(Task = #dreki_task{id = Id, handler = Handler, description = Description, params = Params}) ->
  #{id => Id,
    handler => Handler,
    description => Description,
    params => Params}.