ProvidenceRequestBody.java

package net.morimekta.providence.client.okhttp;

import net.morimekta.providence.PMessage;
import net.morimekta.providence.PServiceCall;
import net.morimekta.providence.serializer.Serializer;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;

public class ProvidenceRequestBody<M extends PMessage<M>> extends RequestBody {
    private final M message;
    private final PServiceCall<M> serviceCall;
    private final Serializer serializer;

    public ProvidenceRequestBody(M message, Serializer serializer) {
        this.message = message;
        this.serviceCall = null;
        this.serializer = serializer;
    }

    public ProvidenceRequestBody(PServiceCall<M> serviceCall, Serializer serializer) {
        this.message = null;
        this.serviceCall = serviceCall;
        this.serializer = serializer;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return MediaType.get(serializer.mediaType());
    }

    @Override
    public void writeTo(@Nonnull BufferedSink bufferedSink) throws IOException {
        if (serviceCall != null) {
            serializer.serialize(bufferedSink.outputStream(), serviceCall);
        } else {
            serializer.serialize(bufferedSink.outputStream(), message);
        }
    }
}