Skip to content

Commit

Permalink
[webui] Add shorten payload in notifications
Browse files Browse the repository at this point in the history
- Add shorten_payload_if_necessary method in Notification model to
ensure that a payload is not bigger than the field size in database.
- Modify the notifiction factory to allow passing parameters to
initialize.
- This should fix openSUSE#4161.

Mobprogrammed with @mdeniz and @DavidKang.
  • Loading branch information
eduardoj committed Jan 4, 2018
1 parent 0f38245 commit 9254a95
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/api/app/models/notification.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,30 @@ class Notification < ApplicationRecord

serialize :event_payload, JSON

def initialize(params = {})
super
shorten_payload_if_necessary
end

def event
@event ||= event_type.constantize.new(event_payload)
end

private

def shorten_payload_if_necessary
return if event.shortenable_key.nil? # If no shortenable_key is set then we cannot shorten the payload

# NOTE: ActiveSupport::JSON is used for serializing ActiveRecord models attributes
overflow_bytes = ActiveSupport::JSON.encode(event_payload).bytesize - 65535

return if overflow_bytes <= 0

# Shorten the payload so it will fit into the database column
shortenable_content = event_payload[event.shortenable_key.to_s]
new_size = shortenable_content.bytesize - overflow_bytes
event_payload[event.shortenable_key.to_s] = shortenable_content.mb_chars.limit(new_size)
end
end

# == Schema Information
Expand Down
2 changes: 2 additions & 0 deletions src/api/spec/factories/notification.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
event_type 'FakeEventType'
event_payload { { fake: 'payload' } }
subscription_receiver_role 'owner'

initialize_with { new(event_type: event_type, event_payload: event_payload, subscription_receiver_role: subscription_receiver_role) }
end

factory :rss_notification, parent: :notification, class: 'Notification::RssFeedItem' do
Expand Down

0 comments on commit 9254a95

Please sign in to comment.