Serialization and deserialization by dynamic `mediaType` In Retrofit - retrofit2

public interface SthApi {
#POST("/")
Call<ApiResult> getSth(#Body ApiReq req, #Header("Content-Type") mediaType);
}
I need serialization and deserialization my ApiReq and ApiResult by dynamic mediaType
What should I do?

Related

How to make Servicestack serialize an implicit string overload the way I want it to?

I have a small class which I am using to make sure the strings sent and received by a service remain URL safe without additional encoding (see below).
Ideally I would like to just apply this type to my DTOs and have Servicestack be smart enough to use the implicit operators.
public class MyDto {
Base64UrlString myString;
}
var dto = new MyDto() { myString = "hello i am url safe"; }
On the client this is received as myString: {}
Is there a more elegant way to do this? I had hoped applying a type this way would "just work"
// used only for Base64UrlEncoder
using Microsoft.IdentityModel.Tokens;
namespace MyDto.ServiceModel.Types
{
public class Base64UrlString
{
private readonly string _base64UrlString;
public Base64UrlString(string str)
{
_base64UrlString = Base64UrlEncoder.Encode(str);
}
public static implicit operator string(Base64UrlString base64UrlString) => base64UrlString.ToString();
public static implicit operator Base64UrlString(string str) => new(str);
public override string ToString() => Base64UrlEncoder.Decode(_base64UrlString);
}
}
You'll need to change your class to a struct to make use of the custom struct behavior you're trying to use in your example.
Also ServiceStack.Text serializers only serializes public properties by default so your DTO should use public properties:
public class MyDto {
public Base64UrlString MyString { get; set; }
}
Alternatively you can configure it to serialize public fields with:
JsConfig.Init(new Config {
IncludePublicFields = true
});

NestJs: Why we don't use DTOs to replace all interfaces?

Can we make DTOs source of truth for the validations, and use it in both controller and service?
If I already have DTOs, why do I need interfaces ?
You don't need interfaces if you don't want to use them. For DTO's which are meant to be basic models, I don't use interfaces either. That being said, they are really powerful so I'm definitely not discouraging you from using them, take this example:
interface ILogger {
log(message: string) : Promise<void>;
}
class ConsoleLogger implements ILogger {
log(message: string) : Promise<void> {
return Promise.resolve(console.log(message));
}
}
class DatabaseLogger implements ILogger {
private dbConnection;
constructor() {
dbConnection = new DBConnection(); //Fake but it drives the point across
}
async log(message: string) : Promise<void> {
return await this.dbConnection.saveLog(message);
}
}
class DoTheThing {
private _logger: ILogger;
//You can have nest inject the best logger for this situation and your code doesn't have to care
//about the actual implementation :)
constructor(logger: ILogger) {
this._logger = logger;
}
async myMethod() {
const tweetMessage = await sendTweet('...');
this._logger.log(tweetMessage);
}
}

Groovy: Delegate instance method to meta class

I'm findind a way easier to implement this kind of feature:
RESTClient client = new RESTClient("https://api.github.com", JSON)
class CoreApi {}
RESTClient.methods*.name.each { name ->
if (! CoreApi.methods.contains(name)) {
CoreApi.metaClass.static."$name" = {Object... args -> client."$name"(*args)}
}
}
and then we can use CoreApi.get(path: "/users/your-user")
Is there any annotation available in groovy for implement this kind of behaviour? What's it called?
You are looking for #Delegate
class CoreApi {
#Delegate RESTClient client
}
But it doesn't work for static methods
Static methods, synthetic methods or methods from the GroovyObject interface are not candidates for delegation

JAX-RS filters calling sequence

My implemention of the JAX-RS Filters as as follows,
The request filter is :
public class AuthorizationRequestFilter implements ContainerRequestFilter {
public static long entryTime;
#Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
/*some preprocessing before unmarshalling*/
}
}
the Response filter is:-
public class ResponseFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
if (!requestContext.getMethod().equalsIgnoreCase("Head")) {
/*Some processing after Marshalling*/
}
}
my handler is :-
#POST
#Path("abc")
#Produces(MediaType.APPLICATION_XML)
public Response createABC(App app){
/*lines of code*/
return Response.status(Status.CRETED).entity(abc).build();
}
My question is are the filters called after Marshallling and Unmarshalling,i.e is the app object created after the method AuthorizationRequestFilter and abc is Marshalled before calling of Response Filter
The request filter is called before unmarshalling. This should be apparent, as you still have access to the entity input stream (meaning it hasn't been read from yet). You could easily test this by writing a trivial MessageBodyReader. Set an arbitrary header in the request filter, then you will be able to extract the same header from the readers readFrom method.
The response filter will be called before the marshalling. Again this could easily be tested by writing a trivial MessageBodyWriter. Set an arbitrary header in the filter, and you should be able to access it in the writer's writeTo method.
If you want to perform some operation after marshalling, you instead could use a WriterInterceptor, which wraps the call the writer's marshalling method. For example
#Provider
public class SimpleIntercetor implements WriterInterceptor{
#Override
public void aroundWriteTo(WriterInterceptorContext context)
throws IOException, WebApplicationException {
// Processing before marshalling
context.proceed(); // marshal
// Processing after marshalling
}
}
Some Resources:
How to Write Custom Entity Providers
Interceptors
The links are to Jersey documentation, but interceptors, readers, writers are standard to JAX-RS 2.0, so the documentation should be applicable to whatever implementation you're using (for the most part :-)

[FromBody]List<BlogUser> items How to rewrite by ServiceStack?

[HttpPut]
public HttpResponseMessage ProcessChecked([FromBody]List<BlogUser> items)
{ }
I can not support it by ServiceStack, How can I write the code?
Every Service in ServiceStack needs to be defined with a single concrete Request DTO. To define a Request DTO that accepts a collection of Types you can inherit from List<T>, e.g:
public class UpdateBlogUsers : List<BlogUser> {}
public object Put(UpdateBlogUsers request)
{
//....
}

Resources