-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathapply_to.rb
More file actions
133 lines (114 loc) · 3.16 KB
/
apply_to.rb
File metadata and controls
133 lines (114 loc) · 3.16 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
require "multi_json"
require_relative "../../validate/decision"
require_relative "../../client"
require_relative "../../router"
require_relative "../../utils/hash_getter"
module Sift
class Client
class Decision
class ApplyTo
PROPERTIES = %w{
source
analyst
description
order_id
session_id
content_id
user_id
account_id
time
}
attr_reader :decision_id, :configs, :getter, :api_key, :client_class
PROPERTIES.each do |attribute|
class_eval %{
def #{attribute}
getter.get(:#{attribute})
end
}
end
def initialize(api_key, decision_id, configs, client_class = Sift::Client)
@api_key = api_key
@decision_id = decision_id
@configs = configs
@getter = Utils::HashGetter.new(configs)
@client_class = client_class
end
def run
if errors.empty?
send_request
else
Response.new(
MultiJson.dump({
status: 55,
error_message: errors.join(", ")
}),
400,
nil
)
end
end
private
def send_request
Router.post(path, {
body: request_body,
headers: headers,
client_class: client_class
})
end
def request_body
{
source: source,
description: description,
analyst: analyst,
decision_id: decision_id,
time: time
}
end
def errors
validator = Validate::Decision.new(configs)
if applying_to_order?
validator.valid_order?
elsif applying_to_session?
validator.valid_session?
elsif applying_to_content?
validator.valid_content?
else
validator.valid_user?
end
validator.error_messages
end
def applying_to_order?
configs.has_key?("order_id") || configs.has_key?(:order_id)
end
def applying_to_session?
configs.has_key?("session_id") || configs.has_key?(:session_id)
end
def applying_to_content?
configs.has_key?("content_id") || configs.has_key?(:content_id)
end
def path
if applying_to_order?
"#{user_path}/orders/#{CGI.escape(order_id)}/decisions"
elsif applying_to_session?
"#{user_path}/sessions/#{CGI.escape(session_id)}/decisions"
elsif applying_to_content?
"#{user_path}/content/#{CGI.escape(content_id)}/decisions"
else
"#{user_path}/decisions"
end
end
def user_path
"#{base_path}/users/#{CGI.escape(user_id)}"
end
def base_path
"#{Client::API3_ENDPOINT}/v3/accounts/#{account_id}"
end
def headers
{
"Content-type" => "application/json"
}.merge(Client.build_auth_header(api_key))
end
end
end
end
end