Skip to content

Commit

Permalink
Allow using the same channel on multiple listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulGilmartin committed Oct 20, 2023
1 parent f03ae8a commit 9078236
Show file tree
Hide file tree
Showing 5 changed files with 15 additions and 4 deletions.
Empty file added .env.dev
Empty file.
Empty file added Dockerfile.dev
Empty file.
12 changes: 10 additions & 2 deletions pgpubsub/listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import Union, Type

import pgtrigger
from pgtrigger import Trigger
from pgtrigger import Trigger, registered

from pgpubsub.channel import (
locate_channel,
Expand Down Expand Up @@ -85,8 +85,16 @@ def _trigger_action_listener(channel, when, operation):
def trigger_listener(channel: Union[Type[Channel], str], trigger: Trigger):
channel = locate_channel(channel)
def _trig_listener(callback):
triggers_already_registered = registered()
model_to_trigger_name = [(model, trig.name) for (model, trig) in triggers_already_registered]

if (channel.model, trigger.name) not in model_to_trigger_name:
# This can happen when the same channel/trigger is used
# for multiple listeners
pgtrigger.register(trigger)(channel.model)

channel.register(callback)
pgtrigger.register(trigger)(channel.model)

@wraps(callback)
def wrapper(*args, **kwargs):
return callback(*args, **kwargs)
Expand Down
5 changes: 5 additions & 0 deletions pgpubsub/tests/listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ def create_first_post_for_author(old: Author, new: Author):
)


@pgpubsub.post_insert_listener(AuthorTriggerChannel)
def another_author_trigger(old: Author, new: Author):
print(f'Another author trigger')


@pgpubsub.post_delete_listener(PostTriggerChannel)
def email_author(old: Post, new: Post):
author = Author.objects.get(pk=old.author_id)
Expand Down
2 changes: 0 additions & 2 deletions pgpubsub/tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import json
from unittest.mock import patch

from django.contrib.auth.models import User
from django.db import connection
from django.db.transaction import atomic
from django.db.migrations.recorder import MigrationRecorder
Expand All @@ -12,7 +11,6 @@
listen_to_channels,
process_notifications,
listen,
NotificationRecoveryProcessor,
)
from pgpubsub.models import Notification
from pgpubsub.notify import process_stored_notifications
Expand Down

0 comments on commit 9078236

Please sign in to comment.