On Wed, 20 Dec 2023 20:36:18 GMT, bomat wrote:
Hi,
I'm currently trying out vibe.d to implement a certain REST API (BCF, but it's not really important for the question) which specifies that any POST request that successfully creates a new record should return status code 201 ("created") - instead of 200 which vibe.d uses as the default success code.
While it's easy to specify error return codes and/or messages, and even register a custom handler for them through
RestInterfaceSettings.errorHandler
, I didn't find anything similar for the success case.I ended up with writing an @after hook, like this:
T setStatusCodeTo201(T)(T result, HTTPServerRequest, HTTPServerResponse response) @safe { response.statusCode = HTTPStatus.created; return result; }
@safe @bodyParam("project") @after!(setStatusCodeTo201!Project)() Project postProjects(Project project);
First of all, I find it kinda ugly that I need to do it as a template just because the @after hook needs to return the same type as the function, although I don't need to manipulate the value, just the header.
And second... well, the whole approach seems hacky and I was wondering if I was missing some obvious and better way to do it.
I just stumbled over this and as far as I can see this is unfortunately the status quo. 2xx status codes are a bit of an oversight in the current API and there needs to be some kind of extension here to make this cleaner. The most straight-forward approach would probably to introduce a @viaStatus
attribute that can be applied to ref
or out
parameters of type HTTPStatusCode
/int
/string
and will be mapped appropriately.
@safe
Project postProjects(
@viaBody("project") Project project,
@viaStatus out HTTPStatus status
)
{
// ...
status = HTTPStatus.created;
return project;
}