Skip to content

Commit

Permalink
Small refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
natenho committed Aug 1, 2019
1 parent 0bd21ca commit c68f3a0
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions src/Mockaco/Templating/TemplateResponseProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@ namespace Mockaco
{
public class TemplateResponseProcessor : ITemplateResponseProcessor
{
private const string JsonContentType = "application/json";
private const HttpStatusCode DefaultHttpStatusCode = HttpStatusCode.OK;

public async Task PrepareResponse(HttpResponse httpResponse, IScriptContext scriptContext, Template template)
{
httpResponse.StatusCode = template.Response.Status == default
? (int)HttpStatusCode.OK
? (int)DefaultHttpStatusCode
: (int)template.Response.Status;

WriteResponseHeaders(httpResponse, template.Response);
Expand All @@ -32,25 +35,33 @@ private void WriteResponseHeaders(HttpResponse response, ResponseTemplate respon

if (string.IsNullOrEmpty(response.ContentType))
{
response.ContentType = "application/json";
response.ContentType = JsonContentType;
}
}

private async Task WriteResponseBody(HttpResponse response, ResponseTemplate responseTemplate)
{
var formatting = responseTemplate.Indented.GetValueOrDefault() ? Formatting.Indented : default;
if(responseTemplate.Body == null)
{
return;
}

var responseBody = responseTemplate.Body?.ToString(formatting);
string responseBody;

if (response.ContentType != "application/json")
//TODO Move to a factory
if (response.ContentType == JsonContentType)
{
responseBody = JsonConvert.DeserializeObject<string>(responseBody);
}
var formatting = responseTemplate.Indented.GetValueOrDefault() ? Formatting.Indented : default;

if (responseBody != null)
responseBody = responseTemplate.Body?.ToString(formatting);
}
else
{
await response.WriteAsync(responseBody);
//Deserializes the JSON string to unescape the body into its raw value
responseBody = JsonConvert.DeserializeObject<string>(responseTemplate.Body?.ToString());
}

await response.WriteAsync(responseBody);
}
}
}

0 comments on commit c68f3a0

Please sign in to comment.