Fix errors

This commit is contained in:
Ali Sadeghi
2025-08-05 00:12:22 +03:30
parent ecaf8b6f2d
commit 0610047aa9
4 changed files with 137 additions and 7 deletions

View File

@@ -0,0 +1,15 @@
package com.sgs.config;
import com.sgs.graphql.scalar.EmissionSourceMapScalar;
import graphql.schema.GraphQLScalarType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GraphQLScalarConfig {
@Bean
public GraphQLScalarType emissionSourceMapScalar() {
return EmissionSourceMapScalar.EmissionSourceMap;
}
}

View File

@@ -0,0 +1,79 @@
package com.sgs.graphql.scalar;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import graphql.language.StringValue;
import graphql.schema.*;
import java.util.Map;
import java.util.HashMap;
public class EmissionSourceMapScalar {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static final GraphQLScalarType EmissionSourceMap = GraphQLScalarType.newScalar()
.name("EmissionSourceMap")
.description("A custom scalar that represents a map of emission sources with their percentages")
.coercing(new Coercing<Map<String, Integer>, String>() {
@Override
public String serialize(Object dataFetcherResult) throws CoercingSerializeException {
if (dataFetcherResult == null) {
return null;
}
try {
if (dataFetcherResult instanceof String) {
return (String) dataFetcherResult;
}
return objectMapper.writeValueAsString(dataFetcherResult);
} catch (Exception e) {
throw new CoercingSerializeException("Unable to serialize EmissionSourceMap", e);
}
}
@Override
public Map<String, Integer> parseValue(Object input) throws CoercingParseValueException {
if (input == null) {
return new HashMap<>();
}
try {
if (input instanceof String) {
String str = (String) input;
if (str.trim().isEmpty()) {
return new HashMap<>();
}
return objectMapper.readValue(str, new TypeReference<Map<String, Integer>>() {});
}
if (input instanceof Map) {
return (Map<String, Integer>) input;
}
return objectMapper.readValue(input.toString(), new TypeReference<Map<String, Integer>>() {});
} catch (Exception e) {
System.err.println("Error parsing EmissionSourceMap: " + e.getMessage());
return new HashMap<>();
}
}
@Override
public Map<String, Integer> parseLiteral(Object input) throws CoercingParseLiteralException {
if (input == null) {
return new HashMap<>();
}
if (input instanceof StringValue) {
try {
String value = ((StringValue) input).getValue();
if (value.trim().isEmpty()) {
return new HashMap<>();
}
return objectMapper.readValue(value, new TypeReference<Map<String, Integer>>() {});
} catch (Exception e) {
System.err.println("Error parsing EmissionSourceMap literal: " + e.getMessage());
return new HashMap<>();
}
}
return new HashMap<>();
}
})
.build();
}