Repositories - AlexGPlay/Blynder GitHub Wiki
Repositores are a bean that is a bit different than the others, in this case, repositories are interfaces, they don't need any method implementation, just the signature. For now, only HTTP Repositories exists, meaning that the only supported type of request is to an API or web server.
The first step is to create an interface and tag it as repository, after that we need another step, this time we have to inherit from another interface.
@Repository
public interface FooRepository extends HttpRepository{
...
}Now we have our repository that can be autowired in any class. It is needed to inherit from HttpRepository so the autowiring process can work. If the @Repository tag or the inheritance is missing, the bean won't work. The next step is to set the request that we are going to send. For the example, we are going to use https://jsonplaceholder.typicode.com/.
@Repository
public interface FooRepository extends HttpRepository{
@Request(url="https://jsonplaceholder.typicode.com/posts")
public HttpResponse fooMethod();
}There are two things that we can see here. There is a new annotation, @Request, this annotations holds two values, the url that will request and the method we will use, we will use this second parameter in the next example. And there is another thing, the return value, it is an HttpResponse, the return type must be always of this type. The HttpResponse holds this data:
- Response
- Status code
- Reason phrase
- Status line
- Protocol version
- Headers
It also holds two methods that can return the response to a Response object that can be returned from a controller and another method called toMap that can convert the response string to a Map, this can be used if the response is a json.
The request can have more information, we can send the segments of the url, the query params, the headers and the body, this parameters can be send using annotations with those names, we will see an example now.
@Repository
public interface FooRepository extends HttpRepository{
@Request(url="https://foo.com", method="POST")
public HttpResponse fooMethod(@Segment List<String> segment,
@Data Map<String, Object> data
@Headers Map<String, Object> headers
@Params Map<String, Object> params);
}This method will hold all that information and will be sent as a POST petition. The data type of the annotations data must be the one given in the example.
Now that we have the bean created we can use it from another bean, we are going to use it from a service so we can see how it works.
@Service
public class FooService{
@Autowired
private FooRepository repo;
public Map<String,Object> getResponse() {
List<String> segments = new ArrayList<String>();
segments.add(String.valueOf(new Random().nextInt(150)+1));
HttpResponse response = repo.getPokemon(segments);
return response.toMap();
}
}In this example we are requesting some information from the FooRepository and given that it is a json we can convert it into a map.