Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class GraphQlObjectParser
- {
- public static string Parse(string queryType, string queryName, string[] subSelection, object @object = null, string objectTypeName = null)
- {
- var query = queryType + "{" + queryName;
- if (@object != null)
- {
- query += "(";
- if (objectTypeName != null)
- {
- query += objectTypeName + ":" + "{";
- }
- var queryData = string.Empty;
- foreach (var propertyInfo in @object.GetType().GetProperties())
- {
- var value = propertyInfo.GetValue(@object);
- if (value != null)
- {
- var type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
- var valueQuotes = type == typeof(string) ? """ : string.Empty;
- var queryPart = char.ToLowerInvariant(propertyInfo.Name[0]) + propertyInfo.Name.Substring(1) + ":" + valueQuotes + value + valueQuotes;
- queryData += queryData.Length > 0 ? "," + queryPart : queryPart;
- }
- }
- query += (objectTypeName != null ? queryData + "}" : queryData) + ")";
- }
- if (subSelection.Length > 0)
- {
- query += subSelection.Aggregate("{", (current, s) => current + (current.Length > 1 ? "," + s : s)) + "}";
- }
- query += "}";
- return query;
- }
- }
- var query = GraphQlObjectParser.Parse("query", "users", new[] { "id", "name" });
- query{users{id,name}}
- var query = GraphQlObjectParser.Parse("query", "user", new[] { "id", "name" }, new User { Id = "1" });
- query{user(id:"1"){id,name}}
- var query = GraphQlObjectParser.Parse("mutation", "user", new[] { "id", "name" }, new User { Id = "1", Name = "John" }, "data");
- mutation{user(data:{id:"1",name:"John"}){id,name}}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement