br.com.m4rc310.gql.mappers.MCoercingUtils Maven / Gradle / Ivy
The newest version!
package br.com.m4rc310.gql.mappers;
import graphql.language.StringValue;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;
/**
* The Class MCoercingUtils.
*
* @author marcelo
* @version $Id: $Id
*/
public class MCoercingUtils {
/**
* Gets the.
*
* @param the generic type
* @param type the type
* @param fromString the from string
* @param toString the to string
* @return the coercing
*/
public static Coercing get(Class type, MFunction fromString,
MFunction toString) {
return new Coercing() {
@Override
@SuppressWarnings("unchecked")
public String serialize(Object dataFetcherResult) throws CoercingSerializeException {
if (type.isInstance(dataFetcherResult)) {
try {
return toString.apply((T) dataFetcherResult);
} catch (Exception e) {
throw new CoercingSerializeException(e.getMessage());
}
}
throw new CoercingSerializeException("Value " + dataFetcherResult + " could not be serialized");
}
@Override
public T parseValue(Object input) throws CoercingParseValueException {
if (type.isInstance(input)) {
return type.cast(input);
}
throw new CoercingSerializeException("Could not be parseValue");
}
@Override
public T parseLiteral(Object input) throws CoercingParseLiteralException {
try {
if (input instanceof StringValue) {
return fromString.apply(((StringValue) input).getValue());
}
if (input instanceof String) {
return fromString.apply((String) input);
}
throw new CoercingSerializeException("Could not be parseValue");
} catch (Exception e) {
throw new CoercingSerializeException(e);
}
}
};
}
/**
* The Interface MFunction.
*
* @param the generic type
* @param the generic type
*/
@FunctionalInterface
public interface MFunction {
/**
* Apply.
*
* @param t the t
* @return the r
* @throws Exception the exception
*/
R apply(T t) throws Exception;
}
}