Files
backend/gateway-service/src/main/java/com/drinkool/controller/GraphqlBase.java
T
TakahashiNguyen aa7bfed331
Release package / release (push) Successful in 22m28s
fix: final commit (#61)
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #61
2026-05-15 14:22:35 +00:00

67 lines
1.8 KiB
Java

package com.drinkool.controller;
import com.drinkool.InternalValue;
import com.drinkool.dtos.GraphqlDto;
import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient;
import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClientBuilder;
import jakarta.inject.Inject;
import jakarta.json.bind.Jsonb;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class GraphqlBase {
@Inject
Jsonb jsonb;
public abstract String getGraphqlUrl();
public Response send(GraphqlDto gqlRequest, HttpHeaders httpHeaders) {
DynamicGraphQLClientBuilder builder =
DynamicGraphQLClientBuilder.newBuilder().url(getGraphqlUrl());
httpHeaders
.getRequestHeaders()
.forEach((name, values) -> {
String headerName = name.toLowerCase();
if (headerName.startsWith(InternalValue.headerId.toLowerCase())) {
if (!values.isEmpty()) {
builder.header(name, values.get(0));
}
}
});
try (DynamicGraphQLClient tempClient = builder.build()) {
io.smallrye.graphql.client.Response response = tempClient.executeSync(
gqlRequest.query,
gqlRequest.variables
);
Map<String, Object> gqlBody = new HashMap<>();
gqlBody.put("data", response.getData());
gqlBody.put("errors", response.getErrors());
return Response.ok(jsonb.toJson(gqlBody))
.type(MediaType.APPLICATION_JSON)
.build();
} catch (Exception e) {
e.printStackTrace();
Map<String, Object> errorBody = new HashMap<>();
errorBody.put(
"errors",
List.of(Map.of("message", "Lỗi kết nối tới service: " + e.getMessage()))
);
return Response.serverError()
.type(MediaType.APPLICATION_JSON)
.entity(jsonb.toJson(errorBody))
.build();
}
}
}