Move body parsing to new fn
This commit is contained in:
parent
d27c38330b
commit
b3c9c3b600
1 changed files with 14 additions and 4 deletions
|
@ -49,11 +49,21 @@ fn respondJson(ctx: *http.server.Context, status: http.Status, value: anytype, a
|
|||
try stream.finish();
|
||||
}
|
||||
|
||||
fn createNote(srv: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void {
|
||||
const body = ctx.request.body orelse return respondJson(ctx, .bad_request, .{ .@"error" = "'content' cannot be empty" }, srv.alloc);
|
||||
fn parseRequestBody(comptime T: type, ctx: *http.server.Context, alloc: std.mem.Allocator) !T {
|
||||
const body = ctx.request.body orelse return error.BodyRequired;
|
||||
var tokens = std.json.TokenStream.init(body);
|
||||
const info = try std.json.parse(api.CreateInfo(models.Note), &tokens, .{ .allocator = srv.alloc });
|
||||
defer std.json.parseFree(api.CreateInfo(models.Note), info, .{ .allocator = srv.alloc });
|
||||
const parsed = try std.json.parse(T, &tokens, .{ .allocator = alloc });
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
fn freeRequestBody(value: anytype, alloc: std.mem.Allocator) void {
|
||||
std.json.parseFree(@TypeOf(value), value, .{ .allocator = alloc });
|
||||
}
|
||||
|
||||
fn createNote(srv: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void {
|
||||
const info = try parseRequestBody(api.CreateInfo(models.Note), ctx, srv.alloc);
|
||||
defer freeRequestBody(info, srv.alloc);
|
||||
|
||||
const note = try srv.api.createNote(info);
|
||||
|
||||
|
|
Loading…
Reference in a new issue