aboutsummaryrefslogtreecommitdiff
path: root/backend/src/main.zig
blob: 21892c89afc172e8a11f641205976470ebb89f36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const Allocator = std.mem.Allocator;
const httpz = @import("httpz");
const std = @import("std");

const repos = @import("repos/repos.zig");

const static = @import("services/static.zig");
const handler = @import("services/handler.zig");
const auth_service = @import("services/auth_service.zig");
const users_service = @import("services/users_service.zig");
const maps_service = @import("services/maps_service.zig");
const markers_service = @import("services/markers_service.zig");

pub fn main() !void {
    // ENV
    const env = std.posix.getenv;
    const port = try std.fmt.parseInt(u16, env("PORT") orelse "3000", 10);
    const db_path = env("DB_PATH") orelse "db.sqlite3";
    const secure_cookies = if (std.mem.eql(u8, env("SECURE_COOKIES") orelse "false", "true")) true else false;

    // Allocator
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    defer _ = gpa.deinit();

    // DB connection
    var conn = try repos.init(allocator, db_path);
    defer conn.close();

    var h = handler.Handler{ .conn = conn, .secure_cookies = secure_cookies };
    var server = try httpz.Server(*handler.Handler).init(allocator, .{
        .port = port,
    }, &h);
    defer server.deinit();
    defer server.stop();

    var router = try server.router(.{});

    const public_route = &handler.RouteData{ .is_public = true };

    // Static files
    router.get("/public/main.css", static.main_css, .{ .data = public_route });
    router.get("/public/main.js", static.main_js, .{ .data = public_route });
    router.get("/public/icon.png", static.icon_png, .{ .data = public_route });

    // API
    router.post("/api/login", auth_service.login, .{ .data = public_route });
    router.post("/api/logout", auth_service.logout, .{});
    router.get("/api/user", users_service.get_user, .{});
    // Maps
    router.get("/api/maps", maps_service.list, .{});
    router.get("/api/maps/:id", maps_service.get, .{});
    router.post("/api/maps", maps_service.create, .{});
    router.put("/api/maps/:id", maps_service.update, .{});
    router.delete("/api/maps/:id", maps_service.delete, .{});
    // Markers
    router.get("/api/markers", markers_service.list_by_map, .{});
    router.post("/api/markers", markers_service.create, .{});
    router.put("/api/markers/:id", markers_service.update, .{});
    router.delete("/api/markers/:id", markers_service.delete, .{});

    std.debug.print("listening http://localhost:{d}/\n", .{port});
    try server.listen();
}