public Task Format() { using (ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { var json = context.ReadForMemory(RequestBodyStream(), "studio-tasks/format"); if (json == null) { throw new BadRequestException("No JSON was posted."); } if (json.TryGet(nameof(FormattedExpression.Expression), out string expressionAsString) == false) { throw new BadRequestException("'Expression' property was not found."); } if (string.IsNullOrWhiteSpace(expressionAsString)) { return(NoContent()); } using (var workspace = new AdhocWorkspace()) { var expression = SyntaxFactory .ParseExpression(expressionAsString) .NormalizeWhitespace(); var result = Formatter.Format(expression, workspace); if (result.ToString().IndexOf("Could not format:", StringComparison.Ordinal) > -1) { throw new BadRequestException(); } var formattedExpression = new FormattedExpression { Expression = result.ToString() }; using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream())) { context.Write(writer, formattedExpression.ToJson()); } } } return(Task.CompletedTask); }
public async Task Format() { using (ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { var json = await context.ReadForMemoryAsync(RequestBodyStream(), "studio-tasks/format"); if (json == null) { throw new BadRequestException("No JSON was posted."); } if (json.TryGet(nameof(FormattedExpression.Expression), out string expressionAsString) == false) { throw new BadRequestException("'Expression' property was not found."); } if (string.IsNullOrWhiteSpace(expressionAsString)) { NoContentStatus(); return; } var type = IndexDefinitionHelper.DetectStaticIndexType(expressionAsString, reduce: null); FormattedExpression formattedExpression; switch (type) { case IndexType.Map: case IndexType.MapReduce: using (var workspace = new AdhocWorkspace()) { var expression = SyntaxFactory .ParseExpression(expressionAsString) .NormalizeWhitespace(); var result = Formatter.Format(expression, workspace); if (result.ToString().IndexOf("Could not format:", StringComparison.Ordinal) > -1) { throw new BadRequestException(); } formattedExpression = new FormattedExpression { Expression = result.ToString() }; } break; case IndexType.JavaScriptMap: case IndexType.JavaScriptMapReduce: formattedExpression = new FormattedExpression { Expression = JSBeautify.Apply(expressionAsString) }; break; default: throw new NotSupportedException($"Unknown index type '{type}'."); } await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream())) { context.Write(writer, formattedExpression.ToJson()); } } }