simialbi / yii2-rest-client

REST client (AR-like model) for Yii Framework 2.0 (via yii2-http-client)
MIT License
20 stars 10 forks source link

How to handle custom Response? #10

Closed juliardi closed 3 years ago

juliardi commented 3 years ago

How to handle custom response? Such as when the data is wrapped like this example from Yii2 documentation site : https://www.yiiframework.com/doc/guide/2.0/en/rest-response-formatting

{
    "items": [
        {
            "id": 1,
            ...
        },
        {
            "id": 2,
            ...
        },
        ...
    ],
    "_links": {
        "self": {
            "href": "http://localhost/users?page=1"
        },
        "next": {
            "href": "http://localhost/users?page=2"
        },
        "last": {
            "href": "http://localhost/users?page=50"
        }
    },
    "_meta": {
        "totalCount": 1000,
        "pageCount": 50,
        "currentPage": 1,
        "perPage": 20
    }
}
simialbi commented 3 years ago

Hi @juliardi How do you use the extension? Could you post some code snippet? What are you trying to achieve?

juliardi commented 3 years ago

I use the extension like the snippet code in the README. The only thing different is my API server, which return a wrapped up data, just like from Yii2 documentation site I mentioned above. I assume that this library, by default, can only populate response data to a model if it is not wrapped. What I am asking is, how to populate a response data to my model, if it is wrapped ?

I am sorry if I am not clear enough.

simialbi commented 3 years ago

I released beta 5 with $itemsProperty in Connection class. You can use like this

    'components' => [
        'rest' => [
            'class' => 'simialbi\yii2\rest\Connection',
            'baseUrl' => 'https://api.site.com/',
            'itemsProperty' => 'items'
        ]
    ]

Please test if it works for you. I would appreciate a feedback :blush:

juliardi commented 3 years ago

I've tested it in my code, and it works in my case. Thanks for your fast response. Just adding my opinion here, maybe it would be better if we can get the response object from the model. Something like this :

$item = MyItem::find()->where(['id' => 1])->one();

$response = $item->getHttpResponse(); // returns 'yii\httpclient\Response' instance here
simialbi commented 3 years ago

Thx for your feedback and proposal. I tried to be as close to the default DB ActiveRecord handling as possible. But I move your proposal to Discussions...