dunglas / mercure

🪽 An open, easy, fast, reliable and battery-efficient solution for real-time communications
https://mercure.rocks
GNU Affero General Public License v3.0
3.98k stars 296 forks source link

Custom topics for API Platform and Mercure #484

Closed alexglvr closed 3 years ago

alexglvr commented 3 years ago

Hello,

I have Mercure working with Api-Platform.

My entities have a field called usergroup, and I want sse messages to be sent only to users that have the same user group.

I thought using custom topics for that.

By default mercure integration in api-platform uses the following form of topics: http://serverIP/api/entityname/{id} (i.e. IRI)

I would need something like http://serverIP/api/entityname/{id}/object.usergroup

Which would permit, in my client app, to subscribe to http://serverIP/api/entityname/{id}/user.usergroup

How can I generate these custom topics via api-platforme & mercure integration? (nb accessing object.usergroup is ok, the problem relly on retreiving the original topic / IRI)

Is there another / better way or filtering message to user groups ?

Thank you for your help

divine commented 3 years ago

Hello,

Here goes an example:

#[ApiResource(
    mercure: "object.mercureOptions()",
)]

class User
{
    public function mercureOptions()
    {
        return [
            'private' => true,
            'topics' => [
                '/users/' . (int) $this->getId(),
                '/groups/' . (int) $this->getGroupId()->getId()
            ]
        ];
    }
}

However, keep in mind that you need to generate correct JWT data for it also:

$payload['mercure'] = ['subscribe' => ['/users/' . $userId, '/groups/' . $groupId']];

Thanks!

stale[bot] commented 3 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.