Dispatch based on path
This commit is contained in:
parent
c26ca37bc0
commit
f891aeafa7
1 changed files with 37 additions and 12 deletions
|
@ -5,10 +5,20 @@ pub fn Router(comptime Context: type) type {
|
||||||
const Self = @This();
|
const Self = @This();
|
||||||
const H = fn (Context) void;
|
const H = fn (Context) void;
|
||||||
|
|
||||||
|
const Route = struct {
|
||||||
|
path: []const u8,
|
||||||
handler: H,
|
handler: H,
|
||||||
|
};
|
||||||
|
|
||||||
pub fn dispatch(self: *const Self, ctx: Context) void {
|
routes: []const Route,
|
||||||
self.handler(ctx);
|
|
||||||
|
pub fn dispatch(self: *const Self, path: []const u8, ctx: Context) void {
|
||||||
|
for (self.routes) |r| {
|
||||||
|
if (std.mem.eql(u8, path, r.path)) {
|
||||||
|
return r.handler(ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unreachable;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -40,16 +50,31 @@ const _tests = struct {
|
||||||
fn dummyHandler(_: Context) void {}
|
fn dummyHandler(_: Context) void {}
|
||||||
|
|
||||||
test "Router(T).dispatch" {
|
test "Router(T).dispatch" {
|
||||||
const call_tracker = CallTracker(.{}, dummyHandler);
|
const mock_a = CallTracker(.{}, dummyHandler);
|
||||||
|
const mock_b = CallTracker(.{}, dummyHandler);
|
||||||
|
const mock_c = CallTracker(.{}, dummyHandler);
|
||||||
|
|
||||||
const router = Router(Context){ .handler = call_tracker.func };
|
const R = Router(Context).Route;
|
||||||
router.dispatch(.{});
|
const routes = [_]R{
|
||||||
try call_tracker.expectCalled(1);
|
.{ .handler = mock_a.func, .path = "/a" },
|
||||||
|
.{ .handler = mock_b.func, .path = "/b" },
|
||||||
|
.{ .handler = mock_c.func, .path = "/c" },
|
||||||
|
};
|
||||||
|
|
||||||
call_tracker.reset();
|
const router = Router(Context){ .routes = &routes };
|
||||||
router.dispatch(.{});
|
router.dispatch("/a", .{});
|
||||||
router.dispatch(.{});
|
try mock_a.expectCalled(1);
|
||||||
router.dispatch(.{});
|
try mock_b.expectCalled(0);
|
||||||
try call_tracker.expectCalled(3);
|
try mock_c.expectCalled(0);
|
||||||
|
|
||||||
|
router.dispatch("/b", .{});
|
||||||
|
try mock_a.expectCalled(1);
|
||||||
|
try mock_b.expectCalled(1);
|
||||||
|
try mock_c.expectCalled(0);
|
||||||
|
|
||||||
|
router.dispatch("/a", .{});
|
||||||
|
try mock_a.expectCalled(2);
|
||||||
|
try mock_b.expectCalled(1);
|
||||||
|
try mock_c.expectCalled(0);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue