Class: Cloudflare::Email

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudflare_workers/email.rb

Defined Under Namespace

Classes: Error

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(js) ⇒ Email

Returns a new instance of Email.



29
30
31
# File 'lib/cloudflare_workers/email.rb', line 29

def initialize(js)
  @js = js
end

Instance Attribute Details

#jsObject (readonly)

Returns the value of attribute js.



27
28
29
# File 'lib/cloudflare_workers/email.rb', line 27

def js
  @js
end

Instance Method Details

#available?Boolean

Returns:

  • (Boolean)


33
34
35
36
# File 'lib/cloudflare_workers/email.rb', line 33

def available?
  js = @js
  !!`(#{js} !== null && #{js} !== undefined && #{js} !== Opal.nil)`
end

#send(to:, from:, subject:, text: nil, html: nil, reply_to: nil) ⇒ Object

Workers ‘env.SEND_EMAIL.send({ to, from, subject, text?, html?, replyTo? })`. `to`: String, Array (nested), or `{ email:, name?: }`; name is forwarded to Workers as `{ email, name }` entries when present. `from` / `reply_to`: String or `{ email:, name?: }`. At least one of `text:` or `html:` is required.

Raises:



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
# File 'lib/cloudflare_workers/email.rb', line 42

def send(to:, from:, subject:, text: nil, html: nil, reply_to: nil)
  js = @js
  err_klass = Cloudflare::Email::Error
  raise Error, 'send_email binding not bound' unless available?

  raise Error, 'subject is required' if subject.nil? || subject.to_s.strip.empty?

  has_text = !(text.nil? || text.to_s.empty?)
  has_html = !(html.nil? || html.to_s.empty?)
  raise Error, 'text or html is required' unless has_text || has_html

  payload = build_send_payload(to: to, from: from, subject: subject.to_s, text: text, html: html, reply_to: reply_to)

  cf = Cloudflare
  # 多行 x-string をメソッド末尾に置くと Opal が Promise を返さない出力になることがあるため return を明示する。
  return `(async function(binding, payload, Kernel, Err, cf) {
    try {
      var r = await binding.send(payload);
      if (r == null || r === undefined) {
        var o0 = {}; o0['message_id'] = ''; o0['cf_send_result_json'] = '"void"';
        return cf.$js_to_ruby(o0);
      }
      var raw = '';
      try { raw = JSON.stringify(r); } catch (x1) { raw = String(r); }
      var mid = r.messageId != null ? String(r.messageId)
        : (r.message_id != null ? String(r.message_id) : '');
      var o = {}; o['message_id'] = mid; o['cf_send_result_json'] = raw;
      return cf.$js_to_ruby(o);
    } catch (e) {
      var code = (e && e.code != null) ? String(e.code) : '';
      var msg = (e && e.message) ? String(e.message) : String(e);
      Kernel.$raise(Err.$new(msg, Opal.hash({ code: code })));
    }
  })(#{js}, #{payload}, #{Kernel}, #{err_klass}, #{cf})`
end