luckyframework / carbon_sendgrid_adapter

MIT License
1 stars 2 forks source link

New custom dyanmic templates #5

Closed jwoertink closed 2 years ago

jwoertink commented 2 years ago

This adds in the ability for an email to specify a Dynamic Template https://docs.sendgrid.com/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates

Dynamic templates are designed and created within the SendGrid website itself. The template builder allows you to specify handlebar type variable placeholders. In the API, you send the template_id, and the dynamic_template_data hash, and SendGrid compiles the email for you to send that.

To use this feature, you would just define two specific methods in your email.

class NotifierEmail < BaseEmail
  def initialize(@user : User)
  end

  def template_id
    "the-special-id-in-sendgrid"
  end

  def dynamic_template_data
    {
      "username" => @user.username,
      "unsub_token" => @user.unsubscribe_token
    }
  end

  to @user
  subject "Notification"
  # note `templates` isn't specified here...
end

NotifierEmail.new(current_user).deliver_now

Since this is pretty custom to SendGrid, I couldn't see a way to make it more generic to be a Carbon specific feature.

jwoertink commented 2 years ago

Ok, it seems there's an issue with how SendGrid determines what to send https://github.com/sendgrid/sendgrid-nodejs/issues/435#issuecomment-970854548 Even though the docs say content is required, my guess is sending the key (even with an empty hash) makes their API throw an error. To circumvent this, you have to add something like:

def html_body
  "0"
end

I'll need to see if there's a way to remove the content key if template_id is not nil to test that it works. Another theory might be that they support some sort of fallback? I haven't seen any docs that mention that, but I wouldn't be surprised if the template_id was invalid, it just used whatever you sent in the content array...

jwoertink commented 2 years ago

Most of the API was implemented using NamedTuple which isn't dynamic. You can't dynamically add in keys, or remove them. The Sendgrid API docs don't mention this, but the theory here is that if you add template_id, you have to remove content otherwise it will try to use that first.

2d59edb refactors the interface to use Hashes so we can add/remove keys dynamically to the params. This also caused a bit of a compiler headache... I'm going to add this to my app to fully test this. If it works, we can keep it in... if not, then I'll revert and consider adding in the html_body "hack" 😝

jwoertink commented 2 years ago

That worked! No need for the html_body hack as long as there's no content key sent when you have template_id defined.