finnow/finnow-api/source/util/json.d

42 lines
1.4 KiB
D
Raw Permalink Normal View History

/// Utilities for reading and writing JSON in HTTP request contexts.
module util.json;
import handy_httpd;
import slf4d;
import asdf;
/**
* Reads a JSON payload into a type T. Throws an `HttpStatusException` if
* the data cannot be read or converted to the given type, with a 400 BAD
* REQUEST status. The type T should not have `const` members.
* Params:
* ctx = The request context to read from.
* Returns: The data that was read.
*/
T readJsonPayload(T)(ref HttpRequestContext ctx) {
try {
string requestBody = ctx.request.readBodyAsString();
return deserialize!T(requestBody);
} catch (SerdeException e) {
debug_("Got an exception while deserializing a request body.", e);
throw new HttpStatusException(HttpStatus.BAD_REQUEST);
}
}
/**
* Writes data of type T to a JSON response body. Throws an `HttpStatusException`
* with status 501 INTERNAL SERVER ERROR if serialization fails.
* Params:
* ctx = The request context to write to.
* data = The data to write.
*/
void writeJsonBody(T)(ref HttpRequestContext ctx, in T data) {
try {
string jsonStr = serializeToJson(data);
ctx.response.writeBodyString(jsonStr, "application/json");
} catch (SerdeException e) {
debug_("Exception while serializing a response body.", e);
throw new HttpStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
}
}