
com.github.tonivade.zeromock.client.HttpClient Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zeromock-client Show documentation
Show all versions of zeromock-client Show documentation
Mock Http Server (mostly) without dependencies
The newest version!
/*
* Copyright (c) 2018-2024, Antonio Gabriel Muñoz Conejo
* Distributed under the terms of the MIT License
*/
package com.github.tonivade.zeromock.client;
import static java.util.Objects.requireNonNull;
import java.lang.reflect.Type;
import com.github.tonivade.purefun.core.Function1;
import com.github.tonivade.purefun.effect.Task;
import com.github.tonivade.purefun.monad.IO;
import com.github.tonivade.purefun.monad.IOOf;
import com.github.tonivade.purefun.type.Try;
import com.github.tonivade.purefun.typeclasses.Instances;
import com.github.tonivade.purejson.PureJson;
import com.github.tonivade.zeromock.api.Bytes;
import com.github.tonivade.zeromock.api.HttpRequest;
import com.github.tonivade.zeromock.api.HttpResponse;
public class HttpClient {
// using IO here because there's no instance for MonadDefer for Id
private final HttpClientK> client;
private HttpClient(HttpClientK> client) {
this.client = requireNonNull(client);
}
public static HttpClient connectTo(String baseUrl) {
return new HttpClient(new HttpClientK<>(baseUrl, Instances.>async()));
}
public HttpResponse request(HttpRequest request) {
return client.request(request).fix(IOOf::toIO).unsafeRunSync();
}
@SafeVarargs
public static Function1> parse(T...reified) {
return parse(HttpClientOf.getClassOf(reified));
}
public static Function1> parse(Class type) {
return parse((Type) type);
}
public static Function1> parse(Type type) {
return response -> Task.fromTry(new PureJson(type).fromJson(Bytes.asString(response.body())))
.flatMap(Task::fromOption).safeRunSync();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy