flugg / laravel-responder

A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.
MIT License
865 stars 86 forks source link

NoopSerializer on empty result(collection, array) #115

Closed cberio closed 6 years ago

cberio commented 6 years ago

when using NoopSerializer, it's okay when there are items in result.

{
    {
        "id" : 1,
        "name": "hello flugger"
    },
    {
        "id" : 2,
        "name": "hello there"
    }
}

but when result are empty. data (resourceKey) appends on results

{
    "data": []
}

what I expected.

{
}
// or []

seems it caused by resolve method?

flugg commented 6 years ago

This doesn't seem right, indeed. I'll take a look at it, thanks :)

cberio commented 6 years ago

first of all, apologies about lack of information. I should wrote more information.

And I figured out that I was using custom Serializer that extends ArraySerializer. NoopSerializer was doing well. its all my mistake!

cberio commented 6 years ago

its make me crazy, there is still 'data' my custom Serializer is belown

class AppSerializer extends ArraySerializer
{
    public function collection($resourceKey, array $data)
    {
        return $resourceKey ? [$resourceKey => $data] : $data;
    }

    public function item($resourceKey, array $data)
    {
        return $resourceKey ? [$resourceKey => $data] : $data;
    }
}

and my controller

public function index()
{
    return responder()->success([])->serializer(new AppSerializer)->respond();
}

and the output

{
    "data": []
}

what do you think about in this case? should I check that data is not empty and if so then set a resourceKey in success methods?

flugg commented 6 years ago

I’ll think about better ways to handle the resourceKey, perhaps a configuration setting for the default resource key when none is found.

For now I think your best solution is to also check if data has items in it, in your condition, like you suggested.

cberio commented 6 years ago

thanks for reapond!

2018년 5월 2일 (수) 22:43, Alexander Tømmerås notifications@github.com님이 작성:

I’ll think about better ways to handle the resourceKey, perhaps a configuration setting for the default resource key when none is found.

For now I think your best solution is to also check if data has items in it, in your condition, like you suggested.

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub https://github.com/flugger/laravel-responder/issues/115#issuecomment-385981998, or mute the thread https://github.com/notifications/unsubscribe-auth/AD_sIYM25hPhrVT1g6wUgPIY6sah4OsKks5tubf_gaJpZM4S8UKi .