All Downloads are FREE. Search and download functionalities are using the official Maven repository.

foundation.cmo.api.mls.graphql.converters.MCoercingUtils Maven / Gradle / Ivy

There is a newer version: 1.0.21
Show newest version
package foundation.cmo.api.mls.graphql.converters;
import graphql.language.StringValue;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;

public class MCoercingUtils {

	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);
				}
			}
		};
	}

	@FunctionalInterface
	public interface MFunction {
		R apply(T t) throws Exception;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy