package com.github.tkocsis.vertx.graphql.model;

import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

public class GraphQLQueryResult {
	
	public static class CannotCastException extends RuntimeException {
		private static final long serialVersionUID = 1L;

		public CannotCastException(String message) {
			super(message);
		}
	}

	private final JsonObject data;
	private final JsonArray errors;
	
	public GraphQLQueryResult(JsonObject data, JsonArray errors) {
		this.data = data;
		this.errors = errors;
	}

	public JsonObject getJson(String queryField) {
		if (data == null) {
			return null;
		}
		return (JsonObject) data.getValue(queryField);
	}
	
	public <T> T getData(String queryField, Class<T> mapTo) {
		if (data == null || data.getValue(queryField) == null) {
			return null;
		}
		Object value = data.getValue(queryField);
		if (mapTo.isAssignableFrom(value.getClass())) {
			return mapTo.cast(value);
		}
		if (value instanceof JsonObject) {
			return ((JsonObject) value).mapTo(mapTo);
		}
		throw new CannotCastException("Can't map " + value.getClass() + " to " + mapTo.getName());
	}
	
	public JsonArray getErrors() {
		if (errors == null) {
			return new JsonArray();
		}
		return errors;
	}
}

@@ -1112,32 +1112,83 @@
 etName());%0A%09%7D%0A%09%0A
+%09public JsonObject getData() %7B%0A%09%09return data;%0A%09%7D%0A%09%0A
 %09public JsonArra
@@ -1277,11 +1277,421 @@
 rors;%0A%09%7D
+%0A%0A%09@Override%0A%09public String toString() %7B%0A%09%09StringBuilder result = new StringBuilder();%0A%09%09result.append(%22data=%22);%0A%09%09if (data != null) %7B%0A%09%09%09result.append(data.encodePrettily()).append(%22; %22);%0A%09%09%7D else %7B%0A%09%09%09result.append(%22null; %22);%0A%09%09%7D%0A%09%09result.append(%22errors=%22);%0A%09%09if (errors != null) %7B%0A%09%09%09result.append(errors.encodePrettily()).append(%22;%22);%0A%09%09%7D else %7B%0A%09%09%09result.append(%22null%22);%0A%09%09%7D%0A%09%09return result.toString();%0A%09%7D
 %0A%7D%0A

add toString and raw getData to GrapQLQueryResult