Adds the Outbox model and its respective migration file

This commit is contained in:
Brusk Awat 2023-03-01 00:42:33 +03:00
parent cbed0bfece
commit 101a2e750c
Signed by: broosk1993
GPG Key ID: 5D20F7E02649F74E
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,25 @@
class CreateOutboxableOutboxes < ActiveRecord::Migration[7.0]
def change
enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
create_table :outboxes, id: :uuid, default: 'gen_random_uuid()' do |t|
t.integer :status, null: false, default: 0
t.string :exchange, null: false, default: ''
t.string :routing_key, null: false, default: ''
t.integer :attempts, null: false, default: 0
t.datetime :last_attempted_at, null: true
t.datetime :retry_at, null: true
t.jsonb :payload, default: {}
t.jsonb :headers, default: {}
t.integer :size, null: false, default: 0
t.references :outboxable, polymorphic: true, null: true
t.timestamps
end
end
end

32
lib/templates/outbox.rb Normal file
View File

@ -0,0 +1,32 @@
class Outbox < ApplicationRecord
attribute :allow_publish, :boolean, default: true
# Callbacks
after_commit :publish, if: :allow_publish?
before_save :check_publishing
# Enums
enum status: { pending: 0, published: 1, failed: 2 }
enum size: { single: 0, batch: 1 }
# Validations
validates :payload, presence: true
validates :exchange, presence: true
validates :routing_key, presence: true
# Associations
belongs_to :outboxable, polymorphic: true, optional: true
def increment_attempt
self.attempts = attempts + 1
self.last_attempted_at = Time.zone.now
end
def publish
Outboxable::Worker.perform_async(id)
end
def check_publishing
self.allow_publish = false if published?
end
end