From ee0ff5687d4002aab20cd91fd28d007d916af36c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 4 Aug 2019 18:01:05 -0400 Subject: add user-friendly doc link & error messages, document validator, improve manifest schema (#654) --- .../Controllers/JsonValidatorController.cs | 49 +++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) (limited to 'src/SMAPI.Web/Controllers') diff --git a/src/SMAPI.Web/Controllers/JsonValidatorController.cs b/src/SMAPI.Web/Controllers/JsonValidatorController.cs index 37393a98..7b755d3b 100644 --- a/src/SMAPI.Web/Controllers/JsonValidatorController.cs +++ b/src/SMAPI.Web/Controllers/JsonValidatorController.cs @@ -113,6 +113,9 @@ namespace StardewModdingAPI.Web.Controllers schema = JSchema.Parse(System.IO.File.ReadAllText(schemaFile.FullName)); } + // get format doc URL + result.FormatUrl = this.GetExtensionField(schema, "@documentationUrl"); + // validate JSON parsed.IsValid(schema, out IList rawErrors); var errors = rawErrors @@ -172,13 +175,22 @@ namespace StardewModdingAPI.Web.Controllers /// The indentation level to apply for inner errors. private string GetFlattenedError(ValidationError error, int indent = 0) { + // get override error + string message = this.GetOverrideError(error.Schema, error.ErrorType); + if (message != null) + return message; + // get friendly representation of main error - string message = error.Message; + message = error.Message; switch (error.ErrorType) { case ErrorType.Enum: message = $"Invalid value. Found '{error.Value}', but expected one of '{string.Join("', '", error.Schema.Enum)}'."; break; + + case ErrorType.Required: + message = $"Missing required fields: {string.Join(", ", (List)error.Value)}."; + break; } // add inner errors @@ -216,5 +228,40 @@ namespace StardewModdingAPI.Web.Controllers return null; } + + /// Get an override error from the JSON schema, if any. + /// The schema or subschema that raised the error. + /// The error type. + private string GetOverrideError(JSchema schema, ErrorType errorType) + { + // get override errors + IDictionary errors = this.GetExtensionField>(schema, "@errorMessages"); + if (errors == null) + return null; + errors = new Dictionary(errors, StringComparer.InvariantCultureIgnoreCase); + + // get matching error + return errors.TryGetValue(errorType.ToString(), out string errorPhrase) + ? errorPhrase + : null; + } + + /// Get an extension field from a JSON schema. + /// The field type. + /// The schema whose extension fields to search. + /// The case-insensitive field key. + private T GetExtensionField(JSchema schema, string key) + { + if (schema.ExtensionData != null) + { + foreach (var pair in schema.ExtensionData) + { + if (pair.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)) + return pair.Value.ToObject(); + } + } + + return default; + } } } -- cgit