4

I have many roles in the app, incl. super_admin, admin, user, moderator, editor ... I want to use apiPlatform and display appropriate fields in entities appropriately for roles, I also made additional classes converting roles into classes. everything works. However, it breaks the idea of groups in the serializer. For example: I have several entities that are related to each other. When I am an admin and want to download entities, all properties with the "admin: read" group will download + all properties from the related classes also with the "admin: read" group, even if I do not use them. Is it okay? Is it a good idea to use roles in entities? There is another better way?

Example from https://api-platform.com/docs/core/serialization/

Class Book

<?php
// api/src/Entity/Book.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;

#[ApiResource(normalizationContext: ['groups' => ['book']])]
class Book
{
    /**
     * @Groups({"book"})
     */
    public $name;

    /**
     * @Groups({"book"})
     */
    public $author;

    // ...
}

Class Person

<?php
// api/src/Entity/Person.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;

#[ApiResource]
class Person
{
    /**
     * ...
     * @Groups("book")
     */
    public $name;

    // ...
}

And result

{
  "@context": "/contexts/Book",
  "@id": "/books/62",
  "@type": "Book",
  "name": "My awesome book",
  "author": {
    "@id": "/people/59",
    "@type": "Person",
    "name": "Kévin Dunglas"
  }
}

So if instead of "book" you type "admin: read" it will always serialize everything that has a group "admin: read". I think it's getting unnecessary data. I want to emphasize that there are a lot of entities, not like in the example of two / several.

ciastekkkk
  • 89
  • 7

1 Answers1

0

I think it's a good idea to add role in the serialization but when you add a role in serialization you should decorate the api_platform.serializer.context_builder see this section https://api-platform.com/docs/core/serialization/#changing-the-serialization-context-dynamically

Youssef Saoubou
  • 591
  • 4
  • 11