const std = @import("std"); const root = @import("root"); const builtin = @import("builtin"); const http = @import("http"); const api = @import("./api.zig"); const Uuid = @import("util").Uuid; pub const auth = @import("./controllers/auth.zig"); pub const notes = @import("./controllers/notes.zig"); pub const actors = @import("./controllers/actors.zig"); pub const utils = struct { const json_options = if (builtin.mode == .Debug) .{ .whitespace = .{ .indent = .{ .Space = 2 }, .separator = true, }, } else .{ .whitespace = .{ .indent = .None, .separator = false, }, }; // Responds to a request with a json value pub fn respondJson(ctx: *http.server.Context, status: http.Status, value: anytype) !void { var headers = http.Headers.init(ctx.alloc); defer headers.deinit(); // Don't need to free this k/v pair because they aren't dynamically allocated try headers.put("Content-Type", "application/json"); var stream = try ctx.openResponse(&headers, status); defer stream.close(); const writer = stream.writer(); try std.json.stringify(value, json_options, writer); try stream.finish(); } pub fn respondError(ctx: *http.server.Context, status: http.Status, err: []const u8) !void { return respondJson(ctx, status, .{ .@"error" = err }); } pub fn parseRequestBody(comptime T: type, ctx: *http.server.Context) !T { const body = ctx.request.body orelse return error.BodyRequired; var tokens = std.json.TokenStream.init(body); const parsed = try std.json.parse(T, &tokens, .{ .allocator = ctx.alloc }); return parsed; } pub fn freeRequestBody(value: anytype, alloc: std.mem.Allocator) void { std.json.parseFree(@TypeOf(value), value, .{ .allocator = alloc }); } pub fn getApiContext(srv: *RequestServer, ctx: *http.server.Context) !api.ApiContext { const header = ctx.request.headers.get("authorization") orelse "(null)"; const token = header[("bearer ").len..]; return try srv.api.makeApiContext(token, ctx.alloc); // TODO: defer api.free(ctx.alloc, user_ctx); } }; const RequestServer = root.RequestServer; const RouteArgs = http.RouteArgs; pub fn healthcheck(_: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void { try utils.respondJson(ctx, .ok, .{ .status = "ok" }); } pub fn notFound(_: *RequestServer, ctx: *http.server.Context) void { utils.respondError(ctx, .not_found, "Not Found") catch unreachable; }