contributte / apitte

:wrench: An opinionated and enjoyable API framework based on Nette Framework. Supporting content negotiation, debugging, middlewares, attributes, annotations and loving openapi/swagger.
https://contributte.org/packages/contributte/apitte/
MIT License
61 stars 37 forks source link

How to add additional data to the root of the response? #96

Closed vylink closed 5 years ago

vylink commented 5 years ago

I'm using decorator to add some additional data into all responses...

class ResponseDecorator implements IResponseDecorator
{
    public function decorateResponse(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $entity = $response->getEntity()->getData();
        $entity['somedata'] = ['id'=>1];

        return $response
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Credentials', 'true')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, DELETE, PUT')
            ->withHeader('Access-Control-Allow-Headers', 'Authorization, Accept, Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-Requested-With, If-Modified-Since, Cache-Control, Location')
            ->withHeader('Access-Control-Max-Age', 1728000)
            ->withEntity(ArrayEntity::from($entity));
    }

}

This returns all responses as following example:

{
    "status": "success",
    "data": {
        "test": "test",
        "somedata": {
            "id": 1
        }
    }
}

My question is if is there any way, how can I move "somedata" node to same level as "status" and "data" nodes.

Cheers

mabar commented 5 years ago

I think you could redefine JsonUnifyTransformer.

What is your usecase for that? Unified data format is mean to be used just for status, data and errors

vylink commented 5 years ago

I would like to send updated authentication token in all responses.... and I'd like to keep "data" node just for actual data... Can you point me how to "redefine JsonUnifyTransformer"?

Kind Regards,

M

mabar commented 5 years ago

Extend JsonUnifyTransfomer and replace service in DIC

services:
    api.negotiation.transformer.json:
        class: App\Api\Transformer\JsonUnifyTransformerTransformer
        alteration: true
mabar commented 5 years ago

You can add these informations to request and response through withAttribute() and get it with getAttribute()

vylink commented 5 years ago

Many thanks. It works!!!