feathersjs-ecosystem / feathers-sync

Synchronize service events between Feathers application instances
MIT License
221 stars 41 forks source link

Determine if event is a synced event #193

Closed palmtown closed 4 months ago

palmtown commented 1 year ago

Steps to reproduce

Hello, this issue is to request a new feature that allows the developer to determine if an event is synced from another server, or if it originated from itself. This would allow a developer to prevent running logic multiple times when new events are received.

The solution suggested at https://github.com/feathersjs-ecosystem/feathers-sync, "If you need to perform actions, for example setting up a first blog post after a new user has been created, add it to the service method itself or use a Feathers hook," presents a problem. When I emit an event from a custom function in my code, it doesn't execute the hook by design thus bypassing any code I may insert into the hook.

Being able to determine if the event is synced or not, would suffice inside of channels.js.

Expected behavior

Variable to check if the event is a synced event or it originated from itself.

Actual behavior

No way to tell if an event is synced from another server or not.

jamesholcomb commented 1 year ago

As a workaround, could you add a field to your data payload that identifies the originating server (e.g. FQN+port, or for example if running on k8s, the POD_NAME)? That would enable conditional actions based on that value.

palmtown commented 1 year ago

@jamesholcomb

Thanks for responding and suggesting a solution. I did review that as a possibility (among others), however, due to the many emits I use throughout my code, it seemed cleaner to do it from feathers-sync which would automatically include any new emits.

Nonetheless, this is a work around.

palmtown commented 4 months ago

As a workaround, could you add a field to your data payload that identifies the originating server (e.g. FQN+port, or for example if running on k8s, the POD_NAME)? That would enable conditional actions based on that value.

@jamesholcomb I revisited this today and found a solution based on your recommendation.

In short, I set a variable named context.eventHost in the before hook, in the app.hooks.js file. This variable is sent along with the payload received by the other hosts; there I can determine if the event originated from self or another host. The end result is, this variable allows me to determine if it is a synced event.

Maybe this is what you meant by "add a field to your data payload"? All-in-all, this approach seems to work, thanks!