volvox/service-chats/src/main/java/io/volvox/chats/ChatResource.java

83 lines
2.3 KiB
Java
Raw Normal View History

2021-11-26 01:01:34 +01:00
package io.volvox.chats;
2021-11-26 18:23:44 +01:00
import io.quarkus.hibernate.reactive.panache.Panache;
2021-11-26 01:01:34 +01:00
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import java.net.URI;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/api/chats")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ChatResource {
@Inject
ChatRepository chatRepository;
@GET
public Multi<Chat> listSessions() {
2021-11-26 01:18:55 +01:00
return chatRepository.streamAll();
2021-11-26 01:01:34 +01:00
}
@GET
@Path("/{id}")
2021-11-26 18:23:44 +01:00
public Uni<Chat> get(@PathParam("id") Long id) {
2021-11-26 01:18:55 +01:00
return chatRepository.findById(id);
2021-11-26 01:01:34 +01:00
}
@POST
public Uni<Response> create(Chat chat) {
2021-11-26 18:23:44 +01:00
return Panache.withTransaction(() -> chatRepository.persist(chat))
.onItem().transform(inserted -> Response.created(URI.create("/api/" + chat.id)).build());
2021-11-26 01:01:34 +01:00
}
@PUT
@Path("/{id}")
2021-11-26 18:23:44 +01:00
public Uni<Chat> update(@PathParam("id") Long id, Chat chat) {
2021-11-26 01:01:34 +01:00
// Find chat by id
2021-11-26 18:23:44 +01:00
return Panache.withTransaction(() -> chatRepository.findById(id)
2021-11-26 01:01:34 +01:00
.flatMap(entity -> {
if (entity == null) {
// Persist the chat if not found
2021-11-26 01:18:55 +01:00
return chatRepository.persist(chat);
2021-11-26 01:01:34 +01:00
} else {
// Update all fields
entity.name = chat.name;
// Return the updated item
return Uni.createFrom().item(entity);
}
2021-11-26 18:23:44 +01:00
}));
2021-11-26 01:01:34 +01:00
}
@DELETE
@Path("/{id}")
2021-11-26 18:23:44 +01:00
public Uni<Void> delete(@PathParam("id") Long id) {
return Panache.withTransaction(() -> chatRepository.findById(id)
2021-11-26 01:01:34 +01:00
.onItem().ifNull().failWith(NotFoundException::new)
2021-11-26 18:23:44 +01:00
.flatMap(chatRepository::delete));
2021-11-26 01:01:34 +01:00
}
@GET
@Path("/search/{username}")
public Uni<Chat> search(@PathParam("username") String username) {
return chatRepository.findByUsername(username);
}
@GET
@Path("/count")
public Uni<Long> count() {
2021-11-26 01:18:55 +01:00
return chatRepository.count();
2021-11-26 01:01:34 +01:00
}
}