Skip to content

Commit

Permalink
Add helper extension to JsonNode
Browse files Browse the repository at this point in the history
  • Loading branch information
simpat-adam committed Jul 18, 2024
1 parent e2fdb7c commit faede87
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,13 @@ public List<JsonNode> GetAllProjectSchemaNodes()
{
JsonNode schema = _apiSchemaRootNode;

KeyValuePair<string, JsonNode?>[]? projectSchemas = schema["projectSchemas"]?.AsObject().ToArray();
if (projectSchemas == null || projectSchemas.Length == 0)
var projectSchemasNode = schema["projectSchemas"];

if (projectSchemasNode == null)
{
string errorMessage = "No projectSchemas found, ApiSchema.json is invalid";
_logger.LogCritical(errorMessage);
throw new InvalidOperationException(errorMessage);
throw new InvalidOperationException("Expected ProjectSchmas node to exist.");
}

List<JsonNode> projectSchemaNodes = projectSchemas
.Where(x => x.Value != null)
.Select(x => x.Value ?? new JsonObject())
.ToList();

return projectSchemaNodes;
return projectSchemasNode.SelectNodesFromPropertyValues();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -244,4 +244,23 @@ public static void TryCoerceStringToNumber(this JsonNode jsonNode)
}
}
}

/// <summary>
/// Helper to extract a list of JsonNodes as the values of all the properties of a JsonNode
/// </summary>
/// <param name="jsonNode"></param>
public static List<JsonNode> SelectNodesFromPropertyValues(this JsonNode jsonNode)
{
KeyValuePair<string, JsonNode?>[]? nodeKeys = jsonNode?.AsObject().ToArray();

if (nodeKeys == null)
{
throw new InvalidOperationException("Unexpected null");
}

return nodeKeys
.Where(x => x.Value != null)
.Select(x => x.Value ?? new JsonObject())
.ToList();
}
}

0 comments on commit faede87

Please sign in to comment.