feat: added method support to router

This commit is contained in:
Sergey Yarkov 2022-03-16 08:53:30 +03:00
parent e17386a782
commit 93c72e36a8
5 changed files with 30 additions and 11 deletions

0
README.md Normal file
View File

View File

@ -3,7 +3,7 @@ import Response from './response.js';
import db from './db.js';
/**
* Get list of all artcles from database
* GET - Get list of all artcles from database
*
* @param {http.ClientRequest} req
* @param {Response} res
@ -14,7 +14,7 @@ export const getArticlesHandler = async (req, res) => {
};
/**
* Get article by ID
* GET - Get article by ID
*
* @param {http.ClientRequest} req
* @param {Response} res
@ -40,3 +40,14 @@ export const getArticleHandler = async (req, res) => {
res.json({ data: data.rows });
};
/**
* POST - Create article
*
* @param {http.ClientRequest} req
* @param {Response} res
*/
export const createArticleHandler = async (req, res) => {
res.json({ data: `POST ${req.url}` });
return;
};

View File

@ -3,7 +3,12 @@ import router from '../router.js';
/**
* Handlers
*/
import { getArticleHandler, getArticlesHandler } from '../handlers.js';
import {
createArticleHandler,
getArticleHandler,
getArticlesHandler,
} from '../handlers.js';
router.define('/api/articles', getArticlesHandler);
router.define('/api/article/:id', getArticleHandler);
router.define('GET', '/api/articles', getArticlesHandler);
router.define('GET', '/api/article/:id', getArticleHandler);
router.define('POST', '/api/article', createArticleHandler);

View File

@ -14,14 +14,16 @@ class Router {
*
* @param {http.ClientRequest} req
* @param {http.ServerResponse} res
* @returns
* @returns {boolean} Is route has been handled
*/
call(req, res) {
const mask = `${req.method}:${req.url}`;
/**
* Find the exact route
*/
if (this.routes.hasOwnProperty(req.url)) {
this.routes[req.url].handler(req, res);
if (this.routes.hasOwnProperty(mask)) {
this.routes[mask].handler(req, res);
return true;
}
@ -35,7 +37,7 @@ class Router {
const route = this.routes[keys[i]];
if (!route.options.exact && route.options.regexp !== undefined) {
const match = req.url.match(route.options.regexp);
if (match) {
if (match && keys[i].includes(req.method)) {
if (route.options.params !== undefined) {
req.params = {};
route.options.params.forEach((param) => {
@ -59,6 +61,7 @@ class Router {
* @param {boolean} exact
*/
define(
method = 'GET',
url,
handler,
options = { exact: true, regexp: undefined, params: undefined }
@ -68,7 +71,8 @@ class Router {
options.exact = false;
options.regexp = pathToRegexp(url, options.params);
}
this.routes[url] = {
this.routes[`${method}:${url}`] = {
method,
handler,
options,
};

View File

@ -48,7 +48,6 @@ class Application {
* Undefined route
*/
if (!handled) response.notFound('Route not found!');
return;
}