ellipsesynergie / api-response

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

[FEATURE] optional resource key #45

Closed emileber closed 6 years ago

emileber commented 6 years ago

In raising this pull request, I confirm the following (please check boxes):

My familiarity with the project is as follows (check one):

If the project maintainer has any additional requirements, they will be listed here.


Makes it easier to override the \EllipseSynergie\ApiResponse\Laravel\ResponseServiceProvider class to change the default serializer.

class OptionalResourceKeyResponseServiceProvider extends ResponseServiceProvider
{
    protected function getSerializer()
    {
        return new OptionalKeySerializer();
    }
}

I also changed the default \EllipseSynergie\ApiResponse\Serializer\Serializer so that when RESOURCE_KEY constant is null, it returns the non-nested data as-is.

This helps remove nested data resource keys for each included resource.

If you still want to keep the root data property to wrap your resource, just specify this within your transformer. (Reference: https://github.com/thephpleague/fractal/issues/299)

public function transform(Foo $foo)
{
    return [
        'data' => [
            'id' => (int) $foo->id,
            // ...etc.
        ]
    ];
}

Or when dealing with includes, specify a resource key when using the response:

return $this->response->withCollection(
    $collection,
    $this->transformer,
    'data'
);

All tests are passing as it doesn't change the default behaviour so it's still backward compatible.