MarcinOrlowski / laravel-api-response-builder

Builds nice, normalized and easy to consume REST JSON responses for Laravel powered APIs.
MIT License
720 stars 80 forks source link

config doesn't seems to be applied #149

Closed bliveinhack closed 4 years ago

bliveinhack commented 4 years ago

What's wrong? I have just installed and publish config.

Now when i simply use

return ResponseBuilder::success(UserType::all(),200);

it gives me response like

{
  "success": true,
  "code": 200,
  "locale": "en",
  "message": "OK",
  "data": {
    "0": {
      "id": 1,
      "description": "User",
      "slug": "USER",
      "created_at": "2020-07-17 22:31:49",
      "updated_at": "2020-07-17 22:31:49"
    },
    "1": {
      "id": 2,
      "description": "Sales",
      "slug": "OTHER_USER",
      "created_at": "2020-07-17 22:31:49",
      "updated_at": "2020-07-17 22:31:49"
    }
  }
}

Steps to reproduce the behavior:

  1. just install fresh stable version 8.0
  2. run vendor publish.
  3. use ResponseBuilder::success() with collection

Expected behavior it should use data converter applied in project and give collection data output without preserving keys...

Runtime environment

Notes

MarcinOrlowski commented 4 years ago

Thanks for the report. Unfortunately I will not be able to look at it before Sep 1st, so please stay tuned.

MarcinOrlowski commented 4 years ago

I suspect that for some reasons invalid converter is being used on your collection. To check that, please update Response Builder to v8.1.0 and enable converter debug logs (i.e. by adding RB_CONVERTER_DEBUG=true to your .env file). Then see the logs.

MarcinOrlowski commented 4 years ago

Ok, so this is not really a bug per se. By design, the data node is always an object, therefore if you want to return an array, you should give it an extra key to avoid output as you shown. This is documented in [https://github.com/MarcinOrlowski/laravel-api-response-builder/blob/master/docs/examples.md](usage examples). The trick here is that you are passing Collection which is then autoconverted to array and then returned, so technically this is exactly that case. In current version you would need to return like this:

RB::success(['my_key' => $collection]);

which would work around that. But I do agree this is ugly. I will think about better approach for next release.

MarcinOrlowski commented 4 years ago

I am closing this ticket as this is not a bug. There's #158 created, please subscribe to it to be informed about further development.

MarcinOrlowski commented 4 years ago

For a record, ths is now implemented as part of dev branch and will appear in v9 shortly.