feat: add the support for routes for all HTTP methods

This commit is contained in:
Dorian Niemiec 2025-01-01 20:12:11 +01:00
parent d2f413c114
commit 80ec67d096
3 changed files with 28 additions and 1 deletions

View file

@ -53,6 +53,8 @@ Parameters:
The function adds a route to the SVRouter router. The function adds a route to the SVRouter router.
If the _method_ parameter is `"*"`, the route will apply to all the methods
The _callback_ parameter has these arguments of the SVR.JS mod callback: The _callback_ parameter has these arguments of the SVR.JS mod callback:
- _req_ - the SVR.JS request object - _req_ - the SVR.JS request object
- _res_ - the SVR.JS response object - _res_ - the SVR.JS response object
@ -98,3 +100,6 @@ An alias to the _router.route("DELETE", path, callback)_ function
### _router.head(path, callback)_ ### _router.head(path, callback)_
An alias to the _router.route("HEAD", path, callback)_ function An alias to the _router.route("HEAD", path, callback)_ function
### _router.all(path, callback)_
An alias to the _router.route("*", path, callback)_ function

View file

@ -14,7 +14,7 @@ function svrouter() {
} }
routes.push({ routes.push({
method: method.toUpperCase(), method: method === "*" ? null : method.toUpperCase(),
pathFunction: match(path), pathFunction: match(path),
callback: callback callback: callback
}); });
@ -96,6 +96,7 @@ function svrouter() {
addRoute(method, path, callback); addRoute(method, path, callback);
}); });
router.all = (path, callback) => addRoute("*", path, callback);
router.route = addRoute; router.route = addRoute;
router.pass = passRoute; router.pass = passRoute;

View file

@ -49,6 +49,27 @@ describe("SVRouter", () => {
expect(res.end).toHaveBeenCalledWith("POST route matched"); expect(res.end).toHaveBeenCalledWith("POST route matched");
}); });
test("should add and handle a route for all HTTP methods", () => {
const req = {
method: "GET",
parsedURL: { pathname: "/test" },
params: null
};
const res = {
end: jest.fn()
};
router.all("/test", (req, res) => {
res.end("GET route matched");
});
router(req, res, null, null, () => {
res.end("No route matched");
});
expect(res.end).toHaveBeenCalledWith("GET route matched");
});
test("should correctly parse parameters in the route", () => { test("should correctly parse parameters in the route", () => {
const req = { const req = {
method: "GET", method: "GET",