How do i handle an api response with a header, response code, and body, using retrofit2? - retrofit2

I have an API that returns a response with a header, status code, and body field. How do I correctly handle this using retrofit, and Kotlin Coroutines? I'm used to a simple implementation such as below, but this does not work since the API is not just the JSON body.
Typical implementation:
interface MyApi {
#GET("myapi")
suspend fun getData() : DataClass
}
With the following response, the above implementation does not work:
{
statusCode=200.0,
headers={
x-custom-header=my custom header value
},
body={
"name":"John",
"message":"Hello"
}
}
Do I need to create a wrapper class for this new type of response? Then, to access the data just call WrapperClass.body? Or is there a more elegant solution to this?

Related

How should I create for nestjs response dto?

How should I create the dto for the nestjs response?
I am currently creating the following code.
I want to define it like the dto of input parameters.
■ response code like this
return {
statusCode: 200,
message: 'successs',
data: {
id: 10
}
}
■ I want to do like this
async test: Promise<SuccessDto> {
return respoinse: SuccessDto
}
I believe there is no need to do that. You can access the code through the headers and the convention is the following
200 is ok / success,
201 is created,
204 is no response,
400 is bad request,
401 is unauthorized,
403 is forbidden,
404 is not found
But to answer your question, it might be possible through interceptors. Their sandbox :
https://github.com/nestjs/nest/blob/master/sample/21-serializer/src/app.controller.ts
use the Res, create a DTO with a generic or a class to extends it and glue it together. Use the #Type(() => YourDTO) to expose what you need. But your kind of reinventing the wheel, NestJS takes care of it and you can overwrite the Response status if needed.

ApolloGateway: How to make a gql call after receiving a response

I have a simple ApolloGateway server, which receives a gql mutation. What I am trying to accomplish is to make another gql mutation upon receiving a success call from the mutation call.
I can see that I can use the method didReceiveResponse in order to handle the received body. However, I am not sure whether there is a better way to do it. Specially, I will need to parse the body, check for the request type, and then make a qgl query, and send an http request, etc.
class SomeRemoteGraphQLDataSource extends RemoteGraphQLDataSource {
async didReceiveResponse(response, req, context) {
const body = await super.didReceiveResponse(response, req, context);
// Do something
return body;
}
}

Modiy axios request 'data' field into 'body'

I'm trying to create a POST request using axios to a Notification API. So this Notification API have been developed before thus I cannot change anything related to it.
It accepts the request more or less like below.
I need to have the request body in the field called body as shown below. However, axios sends the request body in the field called data rather than body
Expected request
{
"head": {
...
},
"body":{
"publicUserId":"abcd",
"merchantId":"123888",
}
},
}
My request composed automatically by axios:
Axios request
{
"head": {
...
},
"data":{
"publicUserId":"abcd",
"merchantId":"123888",
}
},
}
I did try searching for how to alter the request body field name to body instead of data but I'm pretty sure I haven't found the solution. Maybe if anyone here has some workarounds, I'd be glad to try.
Should any details need to be provided, please tell me. Thank you.

Understanding the body decorator in nestjs

Where is the object that references the #body payload stored?
If your user controller has a post function.
#Post() #HttpCode(HttpStatus.CREATED) create(#Body() user: IUserBase):
Promise { return this.usersService.create(user); }
Where is the user variable stored?
Is it stored in the request object of the nest.js server?
It is injected into the function as an argument.
The #body decorator basically says:
Please cast the json that arrives in the request body into IUserBase type and place it as a parameter to this controller's handler.

Servicestack accessing json

My Servicestack service is beeing posted Json (by jquery).
sendData = function(dataToSend) {
var request;
return request = $.ajax({
url: "/api/test",
type: "post",
data: JSON.stringify(dataToSend),
dataType: "json",
accept: "application/json",
contentType: "application/json"
});
The Json data is correctly deserialized if it corresponds to the root properties of my DTO (eg: userId:'foo' -> UserId=foo in the DTO).
I want to access the raw json posted data before it gets deserialized for adding custom deserialization.
Till now I had no problems accessing the querystrings with custom filters (RequestFilterAttribute) or if data vas posted like form.
Now I see the data that gets posted with Chrome Developer Tools is in the headers with "Request Payload" so it is nor in FormData and nor QueryString I can access when debugging my IHttpRequest.
How can I get my raw json data in the filter?
If you want to replace the default deserialization behavior with custom behavior for a specific request DTO, you can do this in your AppHost setup code:
JsConfig<MyRequestDtoClass>.DeSerializeFn = DeserializeMyRequestDto;
Where DeserializeMyRequestDto is a function or lambda taking a single string param - the raw request body - and returning the deserialized instance of your DTO:
MyRequestDtoClass DeserializeMyRequestDto(string rawBody) { ... }
RequestFilterAttribute subclasses purpotedly have access to the raw request body using request.GetRawBody(), where request is the IHttpRequest object passed into the filter's Execute method. But in my experience, GetRawBody returns an empty string, because the request input stream seems to be consumed by that time due to the deserialization. I worked around this once by creating an HTTP module (registered in AppHost via DynamicModuleUtility.RegisterModule) that would "peek" at the request input stream in a BeginRequest event handler. (The "peek" function would read the request input stream and then reset the Position of the stream to where it initially was.)

Resources