Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. public static class GraphQlObjectParser
  2. {
  3. public static string Parse(string queryType, string queryName, string[] subSelection, object @object = null, string objectTypeName = null)
  4. {
  5. var query = queryType + "{" + queryName;
  6.  
  7. if (@object != null)
  8. {
  9. query += "(";
  10.  
  11. if (objectTypeName != null)
  12. {
  13. query += objectTypeName + ":" + "{";
  14. }
  15.  
  16. var queryData = string.Empty;
  17. foreach (var propertyInfo in @object.GetType().GetProperties())
  18. {
  19. var value = propertyInfo.GetValue(@object);
  20. if (value != null)
  21. {
  22. var type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
  23. var valueQuotes = type == typeof(string) ? """ : string.Empty;
  24.  
  25. var queryPart = char.ToLowerInvariant(propertyInfo.Name[0]) + propertyInfo.Name.Substring(1) + ":" + valueQuotes + value + valueQuotes;
  26. queryData += queryData.Length > 0 ? "," + queryPart : queryPart;
  27. }
  28. }
  29. query += (objectTypeName != null ? queryData + "}" : queryData) + ")";
  30. }
  31.  
  32. if (subSelection.Length > 0)
  33. {
  34. query += subSelection.Aggregate("{", (current, s) => current + (current.Length > 1 ? "," + s : s)) + "}";
  35. }
  36.  
  37. query += "}";
  38.  
  39. return query;
  40. }
  41. }
  42.  
  43. var query = GraphQlObjectParser.Parse("query", "users", new[] { "id", "name" });
  44.  
  45. query{users{id,name}}
  46.  
  47. var query = GraphQlObjectParser.Parse("query", "user", new[] { "id", "name" }, new User { Id = "1" });
  48.  
  49. query{user(id:"1"){id,name}}
  50.  
  51. var query = GraphQlObjectParser.Parse("mutation", "user", new[] { "id", "name" }, new User { Id = "1", Name = "John" }, "data");
  52.  
  53. mutation{user(data:{id:"1",name:"John"}){id,name}}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement