GQLUtil.java
package net.morimekta.providence.graphql.gql;
import net.morimekta.providence.PMessage;
import net.morimekta.providence.descriptor.PField;
import net.morimekta.providence.descriptor.PInterfaceDescriptor;
import net.morimekta.util.Binary;
import net.morimekta.util.Strings;
import net.morimekta.util.json.JsonWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
public class GQLUtil {
/**
* Get the based field value for the field. If the containing message is
* implementing an interface, and this field is a field derived from the
* interface, this method will return the interface field of same name.
*
* @param field The field to get base field for.
* @return The base field for the field, or itself.
*/
public static PField<?> baseField(PField<?> field) {
PInterfaceDescriptor<?> ifd = field.onMessageType().getImplementing();
if (ifd != null) {
PField<?> base = ifd.findFieldByName(field.getName());
if (base != null) {
return base;
}
}
return field;
}
public static String toArgumentString(Object o) {
if (o instanceof PMessage) {
PMessage<?> m = (PMessage<?>) o;
StringBuilder builder = new StringBuilder("{");
boolean first = true;
for (PField<?> pf : m.descriptor().getFields()) {
if (m.has(pf.getId())) {
if (!first) {
builder.append(", ");
} else {
first = false;
}
builder.append(pf.getName())
.append(": ")
.append(toArgumentString(m.get(pf.getId())));
}
}
return builder.append("}").toString();
} else if (o instanceof Binary) {
return "\"" + ((Binary) o).toBase64() + "\"";
} else if (o instanceof CharSequence) {
StringWriter writer = new StringWriter();
new JsonWriter(new PrintWriter(writer))
.value((CharSequence) o)
.flush();
return writer.toString();
} else {
return Strings.asString(o);
}
}
}