ellipsesynergie / api-response

Simple package to handle response properly in your API.
MIT License
377 stars 53 forks source link

Changing customKey #33

Closed louisluu closed 7 years ago

louisluu commented 7 years ago

Hi,

What is customKey for? Is customKey working?

Cuz I try to set customKey to something else but it doesnt work

Tried:

return $this->response->withItem($newUser, new UserTransformer, 'user');

and:

return $this->response->withItem($newUser, new UserTransformer, ['key' => 'user']);
maximebeaudoin commented 7 years ago

$this->response->withItem($newUser, new UserTransformer, 'user');should work. Behind the scene, this package create a new Item instance from fractal like this $resource = new Item($data, $transformer, $resourceKey);

louisluu commented 7 years ago

No it did not. I have to create a custom Serializer extends ArraySerializer and put 2 functions in, which are:

        /**
     * Serialize a collection.
     *
     * @param string $resourceKey
     * @param array  $data
     *
     * @return array
     */
    public function collection($resourceKey, array $data)
    {
        return [$resourceKey ? $resourceKey: 'data' => $data];
    }

    /**
     * Serialize an item.
     *
     * @param string $resourceKey
     * @param array  $data
     *
     * @return array
     */
    public function item($resourceKey, array $data)
    {
        return [$resourceKey ? $resourceKey: 'data' => $data];
    }
maximebeaudoin commented 7 years ago

@louisluu You are right, by default, the League\Fractal\Manager class create a League\Fractal\Serializer\DataArraySerializer and the resource key is always data. See http://fractal.thephpleague.com/serializers/ documentation.

However, it's weird that the ArraySerializer doesn't use the key either on the item method. But, this is only my opinion.

To use a custom serializer in the manager instance create by this package, you have to create your own service provider. More detail at https://github.com/ellipsesynergie/api-response/blob/master/src/Laravel/ResponseServiceProvider.php#L42

Hope it's help.

maximebeaudoin commented 7 years ago

@louisluu https://github.com/ellipsesynergie/api-response/commit/edddc75e8b6246145752c17b89c01fccd1eb3e00 will resolve this issue. We will use the code you suggested in the new Serializer we have create.