Symfony and Wildurand/Hateoas Bundle - no links on JSON reposnse

只愿长相守 提交于 2019-12-12 11:38:56

问题


I am using FOSRest and Willdurand/Hateoas bundle. I follow examples from https://github.com/willdurand/Hateoas#configuring-links

but there is no "links" field on JSON response.

/**
 * Users
 *
 * @ORM\Table(name="users")
 * @ORM\Entity
 * @Serializer\ExclusionPolicy("ALL")
 * @Hateoas\Relation("self", href="expr('/users' ~ object.getId())")
 */
class User
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @Serializer\Groups({"Default", "Deserialize"})
     * @Serializer\Expose()
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=30)
     * @Assert\NotBlank()
     * @Assert\Length(max="30", min="5")
     * @Serializer\Groups({"Default", "Deserialize"})
     * @Serializer\Expose()
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=30)
     * @Assert\NotBlank()
     * @Assert\Email()
     * @Assert\Length(max="30")
     * @Serializer\Groups({"Default", "Deserialize"})
     * @Serializer\Expose()
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=15)
     * @Assert\NotBlank()
     * @Assert\Length(max="15", min="3")
     * @Serializer\Groups({"Default", "Deserialize"})
     * @Serializer\Expose()
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=32)
     * @Assert\NotBlank()
     */
    private $password;

    /**
     * @var string
     *
     * @ORM\Column(name="active", type="boolean", length=32)
     * @Serializer\Groups({"Default", "Deserialize"})
     * @Serializer\Expose()
     */
    private $active = true;

    /**
     * @var ArrayCollection
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Role", inversedBy="user")
     * @Serializer\Expose()
     */
    private $roles;

    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param string $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param string $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }

    /**
     * @return string
     */
    public function getActive()
    {
        return $this->active;
    }

    /**
     * @param string $active
     */
    public function setActive($active)
    {
        $this->active = $active;
    }

    /**
     * @return Collection
     */
    public function getRoles()
    {
        return $this->roles;
    }

    /**
     * @param ArrayCollection $roles
     */
    public function setRoles($roles)
    {
        $this->roles = $roles;
    }

}

Mainly I want to show a link to Roles entity but maybe is easier to find out what caused issue for even SELF link and then go further.

Here is configuration

fos_rest:
    routing_loader:
        default_format: json
        include_format: false
    view:
        view_response_listener: 'force'
    body_converter:
        enabled: true
        validate: true
        validation_errors_argument: validationErrors
    param_fetcher_listener: true
    exception:
        enabled: true
        exception_controller: 'AppBundle\Controller\ExceptionController::showAction'
    serializer:
        groups: ['Default']

sensio_framework_extra:
    view:
        annotations: true
    request:
        converters: true

This config is good in meaning that all endpoints work fine except there is no link.

At this point, I get this response on GET request

[
  {
    "id": 1,
    "name": "Test name",
    "email": "test@email.com",
    "username": "toskadv",
    "active": true
  },
  {
    "id": 2,
    "name": "Test name",
    "email": "test@email.com",
    "username": "toskadv",
    "active": true
  },
  {
    "id": 3,
    "name": "Test name",
    "email": "test@email.com",
    "username": "toskadv",
    "active": true,
    "roles": {
      "id": 1,
      "name": "ROLE_USER"
    }
  }
]

There is also controller data.

/**
 * Class UsersController
 * @package AppBundle\Controller
 */
class UsersController extends AbstractController
{
    use ControllerTrait;

    /**
     * @Rest\View()
     */
    public function getUsersAction()
    {
        $users = $this->getDoctrine()->getRepository('AppBundle:User')->findAll();

        return $users;
    }

    /**
     * @param User $user
     * @param ConstraintViolationListInterface $validationErrors
     *
     * @Rest\View(statusCode=201)
     * @ParamConverter("user", converter="fos_rest.request_body")
     * @Rest\NoRoute()
     *
     * @return User $user
     */
    public function postUsersAction(User $user, ConstraintViolationListInterface $validationErrors)
    {
        if (count($validationErrors) > 0) {
            throw new ValidationException($validationErrors);
        }
        $em = $this->getDoctrine()->getManager();
        $role = $em->getRepository('AppBundle:Role')->find(1);
        $user->setRoles($role);

        $em->persist($user);
        $em->flush();

        return $user;
    }

    /**
     * @param User|null $user
     *
     * @Rest\View()
     */
    public function deleteUserAction(User $user = null) {
        if (null === $user) {
            return $this->view(null, 404);
        }

        $em = $this->getDoctrine()->getManager();
        $em->remove($user);
        $em->flush();
    }


    /**
     * @param User $user
     * @return User|\FOS\RestBundle\View\View|null
     *
     * @Rest\View()
     */
    public function getUserAction(User $user)
    {
        if (null === $user) {
            return $this->view(null, 404);
        }

        return $user;
    }

    /**
     * @param Role $role
     * @return Role|\FOS\RestBundle\View\View
     *
     * @Rest\View()
     */
    public function getRoleAction(Role $role)
    {
        if (null === $role) {
            return $this->view(null, 404);
        }

        return $role;
    }

    /**
     * @param User $user
     * @return \Doctrine\Common\Collections\Collection
     *
     * @Rest\View()
     */
    public function getUserRolesAction(User $user)
    {
        return $user->getRoles();
    }

    /**
     * @param User $user
     * @param Role $role
     * @param ConstraintViolationListInterface $validationErrors
     *
     * @Rest\View(statusCode=201)
     * @ParamConverter("role", converter="fos_rest.request_body", options={"deserializationContext"={"groups"={"Deserialize"}}})
     * @Rest\NoRoute()
     *
     * @return Role
     */
    public function postUserRolesAction(User $user, Role $role, ConstraintViolationListInterface $validationErrors)
    {
        if (count($validationErrors) > 0) {
         throw new ValidationException($validationErrors);
        }

        $role->setUser($user);

        $em = $this->getDoctrine()->getManager();
        $user->getRoles()->add($role);

        $em->persist($user);
        $em->flush();

        return $role;
    }
}

回答1:


The problem is that you return the entity, you need to pass from a serializer to get hateoas links.

Something like this:

I use jsm_serializer

$serializer = $this->get('jms_serializer');
return new Response(
     $serializer->serialize(
         $users,
         'json',
         SerializationContext::create()->enableMaxDepthChecks()
     ),
     201
);

instead of this:

return $users;



回答2:


Shame on me :/

Problem was on the first step, I just have not included bundle in AppKernel.php

new Bazinga\Bundle\HateoasBundle\BazingaHateoasBundle(),

this is a missing line. There are no excuses.



来源:https://stackoverflow.com/questions/47532484/symfony-and-wildurand-hateoas-bundle-no-links-on-json-reposnse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!