-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrigger.cr
More file actions
80 lines (60 loc) · 2.24 KB
/
trigger.cr
File metadata and controls
80 lines (60 loc) · 2.24 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
70
71
72
73
74
75
76
77
78
79
80
require "json"
require "rethinkdb-orm"
require "time"
require "./base/model"
require "./trigger/*"
module PlaceOS::Model
class Trigger < ModelBase
include RethinkORM::Timestamps
table :trigger
attribute name : String, es_subfield: "keyword"
attribute description : String = ""
# Full path allows resolution in macros
attribute actions : PlaceOS::Model::Trigger::Actions = ->{ Actions.new }, es_type: "object"
attribute conditions : PlaceOS::Model::Trigger::Conditions = ->{ Conditions.new }, es_type: "object"
# In milliseconds
attribute debounce_period : Int32 = 0
attribute important : Bool = false
attribute enable_webhook : Bool = false
METHODS = %w(GET POST PUT PATCH DELETE)
attribute supported_methods : Array(String) = ["POST"]
# Association
###############################################################################################
secondary_index :authority_id
belongs_to Authority
has_many(
child_class: TriggerInstance,
dependent: :destroy,
foreign_key: "trigger_id",
collection_name: :trigger_instances
)
# Allows filtering in cases of a `Trigger` belonging to a single `ControlSystem`
belongs_to ControlSystem, foreign_key: "control_system_id"
# Validation
###############################################################################################
validates :authority_id, presence: true
# Validate `supported_methods`
validate ->(this : Trigger) do
invalid = this.supported_methods - METHODS
this.validation_error(:supported_methods, "contains invalid methods: #{invalid.join(", ")}") unless invalid.empty?
end
# Validation of `actions` and `conditions`.
validate ->(this : Trigger) do
if !this.actions.valid?
this.actions.errors.each do |e|
this.validation_error(:action, e.to_s)
end
end
if !this.conditions.valid?
this.conditions.errors.each do |e|
this.validation_error(:condition, e.to_s)
end
end
end
# Helpers
###############################################################################################
def supported_method?(method : String)
method.in? supported_methods
end
end
end