GQLUtil.java

  1. package net.morimekta.providence.graphql.gql;

  2. import net.morimekta.providence.PMessage;
  3. import net.morimekta.providence.descriptor.PField;
  4. import net.morimekta.providence.descriptor.PInterfaceDescriptor;
  5. import net.morimekta.util.Binary;
  6. import net.morimekta.util.Strings;
  7. import net.morimekta.util.json.JsonWriter;

  8. import java.io.PrintWriter;
  9. import java.io.StringWriter;

  10. public class GQLUtil {
  11.     /**
  12.      * Get the based field value for the field. If the containing message is
  13.      * implementing an interface, and this field is a field derived from the
  14.      * interface, this method will return the interface field of same name.
  15.      *
  16.      * @param field The field to get base field for.
  17.      * @return The base field for the field, or itself.
  18.      */
  19.     public static PField<?> baseField(PField<?> field) {
  20.         PInterfaceDescriptor<?> ifd = field.onMessageType().getImplementing();
  21.         if (ifd != null) {
  22.             PField<?> base = ifd.findFieldByName(field.getName());
  23.             if (base != null) {
  24.                 return base;
  25.             }
  26.         }
  27.         return field;
  28.     }

  29.     public static String toArgumentString(Object o) {
  30.         if (o instanceof PMessage) {
  31.             PMessage<?>   m       = (PMessage<?>) o;
  32.             StringBuilder builder = new StringBuilder("{");
  33.             boolean       first   = true;
  34.             for (PField<?> pf : m.descriptor().getFields()) {
  35.                 if (m.has(pf.getId())) {
  36.                     if (!first) {
  37.                         builder.append(", ");
  38.                     } else {
  39.                         first = false;
  40.                     }
  41.                     builder.append(pf.getName())
  42.                            .append(": ")
  43.                            .append(toArgumentString(m.get(pf.getId())));
  44.                 }
  45.             }
  46.             return builder.append("}").toString();
  47.         } else if (o instanceof Binary) {
  48.             return "\"" + ((Binary) o).toBase64() + "\"";
  49.         } else if (o instanceof CharSequence) {
  50.             StringWriter writer = new StringWriter();
  51.             new JsonWriter(new PrintWriter(writer))
  52.                     .value((CharSequence) o)
  53.                     .flush();
  54.             return writer.toString();
  55.         } else {
  56.             return Strings.asString(o);
  57.         }
  58.     }
  59. }