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 H = fn (Context) void;
|
||||
|
||||
handler: H,
|
||||
const Route = struct {
|
||||
path: []const u8,
|
||||
handler: H,
|
||||
};
|
||||
|
||||
pub fn dispatch(self: *const Self, ctx: Context) void {
|
||||
self.handler(ctx);
|
||||
routes: []const Route,
|
||||
|
||||
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 {}
|
||||
|
||||
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 };
|
||||
router.dispatch(.{});
|
||||
try call_tracker.expectCalled(1);
|
||||
const R = Router(Context).Route;
|
||||
const routes = [_]R{
|
||||
.{ .handler = mock_a.func, .path = "/a" },
|
||||
.{ .handler = mock_b.func, .path = "/b" },
|
||||
.{ .handler = mock_c.func, .path = "/c" },
|
||||
};
|
||||
|
||||
call_tracker.reset();
|
||||
router.dispatch(.{});
|
||||
router.dispatch(.{});
|
||||
router.dispatch(.{});
|
||||
try call_tracker.expectCalled(3);
|
||||
const router = Router(Context){ .routes = &routes };
|
||||
router.dispatch("/a", .{});
|
||||
try mock_a.expectCalled(1);
|
||||
try mock_b.expectCalled(0);
|
||||
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…
Reference in a new issue