Browse Source

chore: updates README.md and renames the method `router.requestHandler` to `router.requestListener`

e22m4u 1 year ago
parent
commit
285a14c183

+ 109 - 81
README.md

@@ -1,70 +1,72 @@
 ## @e22m4u/js-trie-router
 ## @e22m4u/js-trie-router
 
 
-A pure ES-module of the Node.js HTTP router that uses the
-[Trie](https://en.wikipedia.org/wiki/Trie) for routing.
+ES-модуль HTTP роутера для Node.js, использующий
+[Trie](https://en.wikipedia.org/wiki/Trie)
+для разрешения маршрутов.
 
 
-- Uses [path-to-regexp](https://github.com/pillarjs/path-to-regexp) syntax.
-- Supports path parameters.
-- Parses JSON-body automatically.
-- Parses a query string and a `cookie` header.
-- Supports `preHandler` and `postHandler` hooks.
-- Asynchronous request handler.
+- Поддержка [path-to-regexp](https://github.com/pillarjs/path-to-regexp) синтаксиса.
+- Автоматический парсинг JSON-тела запроса.
+- Парсинг строки запроса и заголовка `cookie`.
+- Поддержка `preHandler` и `postHandler` хуков.
+- Позволяет использовать асинхронные обработчики.
 
 
-## Installation
+## Установка
 
 
 ```bash
 ```bash
 npm install @e22m4u/js-trie-router
 npm install @e22m4u/js-trie-router
 ```
 ```
 
 
-To load an ES-module set `"type": "module"` in the `package.json`
-or use the `.mjs` extension.
+Для загрузки ES-модуля требуется установить `"type": "module"` в файле
+`package.json`, или использовать `.mjs` расширение.
 
 
-## Overview
+## Обзор
 
 
-A basic "Hello world." example.
+Базовый пример создания экземпляра роутера, объявления маршрута
+и передачи слушателя запросов `http` серверу.
 
 
 ```js
 ```js
 import http from 'http';
 import http from 'http';
-import {TrieRouter} from '../src/index.js';
-import {HTTP_METHOD} from '../src/route.js';
+import {TrieRouter} from '@e22m4u/js-path-trie';
 
 
-const server = new http.Server(); // A Node.js HTTP server.
-const router = new TrieRouter();  // A TrieRouter instance.
+const server = new http.Server(); // создание экземпляра HTTP сервера
+const router = new TrieRouter();  // создание экземпляра роутера
 
 
 router.defineRoute({
 router.defineRoute({
-  method: HTTP_METHOD.GET,        // Request method.
-  path: '/',                      // Path template like "/user/:id".
-  handler(ctx) {                  // Request handler.
+  method: 'GET',                  // метод запроса "GET", "POST" и т.д.
+  path: '/',                      // шаблон пути, пример "/user/:id"
+  handler(ctx) {                  // обработчик маршрута
     return 'Hello world!';
     return 'Hello world!';
   },
   },
 });
 });
 
 
-server.on('request', router.requestHandler);
-server.listen(3000, 'localhost');
+server.on('request', router.requestListener); // подключение роутера
+server.listen(3000, 'localhost');             // прослушивание запросов
 
 
 // Open in browser http://localhost:3000
 // Open in browser http://localhost:3000
 ```
 ```
 
 
-### RequestContext
+### Контекст запроса
 
 
-The first parameter of a route handler is a `RequestContext` instance.
+Первый параметр обработчика маршрута принимает экземпляр класса
+`RequestContext` с набором свойств, содержащих разобранные
+данные входящего запроса.
 
 
-- `container: ServiceContainer` is an instance of the [ServiceContainer](https://npmjs.com/package/@e22m4u/js-service)
-- `req: IncomingMessage` is a native request from the `http` module
-- `res: ServerResponse` is a native response from the `http` module
-- `params: ParsedParams` is a key-value object of path parameters
-- `query: ParsedQuery` is a key-value object of a parsed query string
-- `headers: ParsedHeaders` is a key-value object of request headers
-- `cookie: ParsedCookie` is a key-value object of a parsed `cookie` header
-- `method: string` is a request method in lower case like `get`, `post` etc.
-- `path: string` is a request pathname with a query string
-- `pathname: string` is a request pathname without a query string
+- `container: ServiceContainer` экземпляр [сервис-контейнера](https://npmjs.com/package/@e22m4u/js-service)
+- `req: IncomingMessage` нативный поток запроса модуля `http`
+- `res: ServerResponse` нативный поток ответа модуля `http`
+- `params: ParsedParams` объект ключ-значение с параметрами пути
+- `query: ParsedQuery` объект ключ-значение с параметрами строки запроса
+- `headers: ParsedHeaders` объект ключ-значение с заголовками запроса 
+- `cookie: ParsedCookie` объект ключ-значение разобранного заголовка `cookie`
+- `method: string` метод запроса в верхнем регистре, например `GET`, `POST` и т.д.
+- `path: string` путь включающий строку запроса, например `/myPath?foo=bar`
+- `pathname: string` путь запроса, например `/myMath`
 
 
-Here are example values of RequestContext properties.
+Пример доступа к контексту из обработчика маршрута.
 
 
 ```js
 ```js
 router.defineRoute({
 router.defineRoute({
-  method: 'get',
+  method: 'GET',
   path: '/users/:id',
   path: '/users/:id',
   handler(ctx) {
   handler(ctx) {
     // GET /users/10?include=city
     // GET /users/10?include=city
@@ -75,7 +77,7 @@ router.defineRoute({
     console.log(ctx.query);    // {include: 'city'}
     console.log(ctx.query);    // {include: 'city'}
     console.log(ctx.headers);  // {cookie: 'foo=bar; baz=qux;'}
     console.log(ctx.headers);  // {cookie: 'foo=bar; baz=qux;'}
     console.log(ctx.cookie);   // {foo: 'bar', baz: 'qux'}
     console.log(ctx.cookie);   // {foo: 'bar', baz: 'qux'}
-    console.log(ctx.method);   // "get"
+    console.log(ctx.method);   // "GET"
     console.log(ctx.path);     // "/users/10?include=city"
     console.log(ctx.path);     // "/users/10?include=city"
     console.log(ctx.pathname); // "/users/10"
     console.log(ctx.pathname); // "/users/10"
     // ...
     // ...
@@ -83,9 +85,12 @@ router.defineRoute({
 });
 });
 ```
 ```
 
 
-### Sending response
+### Отправка ответа
 
 
-Return values of a route handler will be sent as described below.
+Возвращаемое значение обработчика маршрута используется в качестве ответа
+сервера. Тип значения влияет на представление возвращаемых данных. Например,
+если результатом будет являться тип `object`, то такое значение автоматически
+сериализуется в JSON.
 
 
 | value     | content-type             |
 | value     | content-type             |
 |-----------|--------------------------|
 |-----------|--------------------------|
@@ -96,20 +101,19 @@ Return values of a route handler will be sent as described below.
 | `Buffer`  | application/octet-stream |
 | `Buffer`  | application/octet-stream |
 | `Stream`  | application/octet-stream |
 | `Stream`  | application/octet-stream |
 
 
-Here is an example of a JSON response.
+Пример возвращаемого значения обработчиком маршрута.
 
 
 ```js
 ```js
-router.defineRoute({
+router.defineRoute({     // регистрация маршрута
   // ...
   // ...
-  handler(ctx) {
-    // sends "application/json"
-    return {foo: 'bar'};
+  handler(ctx) {         // обработчик входящего запроса
+    return {foo: 'bar'}; // ответ будет представлен в виде JSON
   },
   },
 });
 });
 ```
 ```
 
 
-If the `ServerResponse` has been sent manually, then a return
-value of the route handler will be ignored.
+Контекст запроса `ctx` содержит нативный экземпляр класса `ServerResponse`,
+который может быть использован для ручного управления ответом.
 
 
 ```js
 ```js
 router.defineRoute({
 router.defineRoute({
@@ -122,32 +126,60 @@ router.defineRoute({
 });
 });
 ```
 ```
 
 
-### Route hooks
+### Хуки маршрута
+
+Определение маршрута методом `defineRoute` позволяет задать хуки
+для отслеживания и перехвата входящего запроса и ответа
+конкретного маршрута.
 
 
-A route definition allows you to set following hooks:
+- `preHandler` выполняется перед вызовом обработчика
+- `postHandler` выполняется после вызова обработчика
 
 
-- `preHandler` is executed before a route handler.
-- `postHandler` is executed after a route handler.
+#### preHandler
 
 
-If the `preHandler` hook returns a value other than `undefined`
-or `null`, it will be used as the server response.
+Перед вызовом обработчика маршрута может потребоваться выполнение
+таких операции как авторизация и проверка параметров запроса. Для
+этого можно использовать хук `preHandler`.
 
 
 ```js
 ```js
-router.defineRoute({
+router.defineRoute({ // регистрация маршрута
   // ...
   // ...
   preHandler(ctx) {
   preHandler(ctx) {
-    return 'Are you authenticated?';
+    // вызывается перед обработчиком
+    console.log(`Incoming request ${ctx.method} ${ctx.path}`);
+    // Incoming request GET /myPath
   },
   },
   handler(ctx) {
   handler(ctx) {
-    // the request handler will be skipped because
-    // the "preHandler" hook returns a non-empty value
     return 'Hello world!';
     return 'Hello world!';
   },
   },
 });
 });
 ```
 ```
 
 
-A return value of the route handler will be passed as the second
-argument to the `preHandler` hook.
+Если хук `preHandler` возвращает значение отличное от `undefined` и `null`,
+то такое значение будет использовано в качестве ответа сервера, а вызов
+обработчика маршрута будет пропущен.
+
+```js
+router.defineRoute({ // регистрация маршрута
+  // ...
+  preHandler(ctx) {
+    // возвращение ответа сервера
+    return 'Are you authorized?';
+  },
+  handler(ctx) {
+    // данный обработчик не вызывается, так как
+    // хук "preHandler" уже отправил ответ
+  },
+});
+```
+
+#### postHandler
+
+Возвращаемое значение обработчика маршрута передается вторым аргументом
+хука `postHandler`. По аналогии с `preHandler`, если возвращаемое
+значение отличается от `undefined` и `null`, то такое значение будет
+использовано в качестве ответа сервера. Это может быть полезно для
+модификации возвращаемого ответа.
 
 
 ```js
 ```js
 router.defineRoute({
 router.defineRoute({
@@ -155,57 +187,53 @@ router.defineRoute({
   handler(ctx) {
   handler(ctx) {
     return 'Hello world!';
     return 'Hello world!';
   },
   },
-  preHandler(ctx, data) {
-    // after the route handler
+  postHandler(ctx, data) {
+    // выполняется после обработчика маршрута
     return data.toUpperCase(); // HELLO WORLD!
     return data.toUpperCase(); // HELLO WORLD!
   },
   },
 });
 });
 ```
 ```
 
 
-### Global hooks
+### Глобальные хуки
 
 
-A `Router` instance allows you to set following global hooks:
+Экземпляр роутера `TrieRouter` позволяет задать глобальные хуки, которые
+имеют более высокий приоритет перед хуками маршрута, и вызываются
+в первую очередь.
 
 
-- `preHandler` is executed before each route handler.
-- `postHandler` is executed after each route handler.
+- `preHandler` выполняется перед вызовом обработчика
+- `postHandler` выполняется после вызова обработчика
 
 
-The `addHook` method of a `Router` instance accepts a hook name as the first
-parameter and a hook function as the second.
+Добавить глобальные хуки можно методом `addHook` экземпляра роутера,
+где первым параметром передается название хука, а вторым его функция.
 
 
 ```js
 ```js
 router.addHook('preHandler', (ctx) => {
 router.addHook('preHandler', (ctx) => {
-  // executes before each route handler
+  // вызов перед обработчиком маршрута
 });
 });
 
 
 router.addHook('postHandler', (ctx, data) => {
 router.addHook('postHandler', (ctx, data) => {
-  // executes after each route handler
+  // вызов после обработчика маршрута
 });
 });
 ```
 ```
 
 
-Similar to a route hook, if a global hook returns a value other than
-`undefined` or `null`, that value will be used as the server response.
+Аналогично хукам маршрута, если глобальный хук возвращает значение
+отличное от `undefined` и `null`, то такое значение будет использовано
+как ответ сервера.
 
 
-## Debug
+## Отладка
 
 
-Set environment variable `DEBUG=jsTrieRouter*` before start.
+Установка переменной `DEBUG` перед командой запуска включает вывод логов.
 
 
 ```bash
 ```bash
 DEBUG=jsPathTrie* npm run test
 DEBUG=jsPathTrie* npm run test
 ```
 ```
 
 
-## Testing
+## Тестирование
 
 
 ```bash
 ```bash
 npm run test
 npm run test
 ```
 ```
 
 
-## Contribution
-
-- Bug fixes.
-- Grammar correction.
-- Documentation improvements.
-- Vulnerability fixes.
-
-## License
+## Лицензия
 
 
 MIT
 MIT

+ 1 - 1
examples/cookie-parsing-example.js

@@ -15,7 +15,7 @@ router.defineRoute({
 // создаем экземпляр HTTP сервера
 // создаем экземпляр HTTP сервера
 // и подключаем обработчик запросов
 // и подключаем обработчик запросов
 const server = new http.Server();
 const server = new http.Server();
-server.on('request', router.requestHandler);
+server.on('request', router.requestListener);
 
 
 // слушаем входящие запросы
 // слушаем входящие запросы
 // на указанный адрес и порт
 // на указанный адрес и порт

+ 1 - 1
examples/params-parsing-example.js

@@ -15,7 +15,7 @@ router.defineRoute({
 // создаем экземпляр HTTP сервера
 // создаем экземпляр HTTP сервера
 // и подключаем обработчик запросов
 // и подключаем обработчик запросов
 const server = new http.Server();
 const server = new http.Server();
-server.on('request', router.requestHandler);
+server.on('request', router.requestListener);
 
 
 // слушаем входящие запросы
 // слушаем входящие запросы
 // на указанный адрес и порт
 // на указанный адрес и порт

+ 1 - 1
examples/query-parsing-example.js

@@ -15,7 +15,7 @@ router.defineRoute({
 // создаем экземпляр HTTP сервера
 // создаем экземпляр HTTP сервера
 // и подключаем обработчик запросов
 // и подключаем обработчик запросов
 const server = new http.Server();
 const server = new http.Server();
-server.on('request', router.requestHandler);
+server.on('request', router.requestListener);
 
 
 // слушаем входящие запросы
 // слушаем входящие запросы
 // на указанный адрес и порт
 // на указанный адрес и порт

+ 1 - 1
examples/uptime-example.js

@@ -27,7 +27,7 @@ router.defineRoute({
 // создаем экземпляр HTTP сервера
 // создаем экземпляр HTTP сервера
 // и подключаем обработчик запросов
 // и подключаем обработчик запросов
 const server = new http.Server();
 const server = new http.Server();
-server.on('request', router.requestHandler);
+server.on('request', router.requestListener);
 
 
 // слушаем входящие запросы
 // слушаем входящие запросы
 // на указанный адрес и порт
 // на указанный адрес и порт

+ 1 - 1
package.json

@@ -1,7 +1,7 @@
 {
 {
   "name": "@e22m4u/js-trie-router",
   "name": "@e22m4u/js-trie-router",
   "version": "0.0.2",
   "version": "0.0.2",
-  "description": "Trie-based router for Node.js",
+  "description": "Trie-роутер для Node.js",
   "type": "module",
   "type": "module",
   "main": "src/index.js",
   "main": "src/index.js",
   "scripts": {
   "scripts": {

+ 2 - 2
src/parsers/body-parser.js

@@ -11,7 +11,7 @@ import {parseContentType} from '../utils/parse-content-type.js';
  *
  *
  * @type {string[]}
  * @type {string[]}
  */
  */
-export const METHODS_WITH_BODY = ['post', 'put', 'patch', 'delete'];
+export const METHODS_WITH_BODY = ['POST', 'PUT', 'PATCH', 'DELETE'];
 
 
 /**
 /**
  * Unparsable media types.
  * Unparsable media types.
@@ -100,7 +100,7 @@ export class BodyParser extends Service {
    * @returns {Promise<*>|undefined}
    * @returns {Promise<*>|undefined}
    */
    */
   parse(req) {
   parse(req) {
-    if (!METHODS_WITH_BODY.includes(req.method.toLowerCase())) {
+    if (!METHODS_WITH_BODY.includes(req.method.toUpperCase())) {
       this.debug(
       this.debug(
         'Body parsing was skipped for the %s request.',
         'Body parsing was skipped for the %s request.',
         req.method.toUpperCase(),
         req.method.toUpperCase(),

+ 1 - 1
src/request-context.js

@@ -70,7 +70,7 @@ export class RequestContext {
    * @returns {string}
    * @returns {string}
    */
    */
   get method() {
   get method() {
-    return this.req.method.toLowerCase();
+    return this.req.method.toUpperCase();
   }
   }
 
 
   /**
   /**

+ 3 - 3
src/request-context.spec.js

@@ -88,12 +88,12 @@ describe('RequestContext', function () {
   });
   });
 
 
   describe('method', function () {
   describe('method', function () {
-    it('returns the method name in lower case', function () {
-      const req = createRequestMock({method: 'POST'});
+    it('returns the method name in upper case', function () {
+      const req = createRequestMock({method: 'post'});
       const res = createResponseMock();
       const res = createResponseMock();
       const cnt = new ServiceContainer();
       const cnt = new ServiceContainer();
       const ctx = new RequestContext(cnt, req, res);
       const ctx = new RequestContext(cnt, req, res);
-      expect(ctx.method).to.be.eq('post');
+      expect(ctx.method).to.be.eq('POST');
     });
     });
   });
   });
 
 

+ 1 - 1
src/route-registry.js

@@ -61,7 +61,7 @@ export class RouteRegistry extends Service {
       req.method.toUpperCase(),
       req.method.toUpperCase(),
       requestPath,
       requestPath,
     );
     );
-    const triePath = `${req.method.toLowerCase()}/${requestPath}`;
+    const triePath = `${req.method.toUpperCase()}/${requestPath}`;
     const resolved = this._trie.match(triePath);
     const resolved = this._trie.match(triePath);
     if (resolved) {
     if (resolved) {
       const route = resolved.value;
       const route = resolved.value;

+ 11 - 11
src/route.js

@@ -22,19 +22,19 @@ import {getRequestPathname} from './utils/index.js';
  * Http method.
  * Http method.
  *
  *
  * @type {{
  * @type {{
- *   DELETE: 'delete',
- *   POST: 'post',
- *   GET: 'get',
- *   PUT: 'put',
- *   PATCH: 'patch',
+ *   GET: 'GET',
+ *   POST: 'POST',
+ *   PUT: 'PUT',
+ *   PATCH: 'PATCH',
+ *   DELETE: 'DELETE',
  * }}
  * }}
  */
  */
 export const HTTP_METHOD = {
 export const HTTP_METHOD = {
-  GET: 'get',
-  POST: 'post',
-  PUT: 'put',
-  PATCH: 'patch',
-  DELETE: 'delete',
+  GET: 'GET',
+  POST: 'POST',
+  PUT: 'PUT',
+  PATCH: 'PATCH',
+  DELETE: 'DELETE',
 };
 };
 
 
 /**
 /**
@@ -134,7 +134,7 @@ export class Route {
           'a non-empty String, but %v given.',
           'a non-empty String, but %v given.',
         routeDef.method,
         routeDef.method,
       );
       );
-    this._method = routeDef.method.toLowerCase();
+    this._method = routeDef.method.toUpperCase();
     if (typeof routeDef.path !== 'string')
     if (typeof routeDef.path !== 'string')
       throw new Errorf(
       throw new Errorf(
         'The option "path" of the Route should be ' + 'a String, but %v given.',
         'The option "path" of the Route should be ' + 'a String, but %v given.',

+ 3 - 3
src/route.spec.js

@@ -195,13 +195,13 @@ describe('Route', function () {
       throwable2(() => undefined)();
       throwable2(() => undefined)();
     });
     });
 
 
-    it('sets the option "method" in lowercase to the "method" property', function () {
+    it('sets the option "method" in upper case to the "method" property', function () {
       const route = new Route({
       const route = new Route({
-        method: 'POST',
+        method: 'post',
         path: '/',
         path: '/',
         handler: () => undefined,
         handler: () => undefined,
       });
       });
-      expect(route.method).to.be.eq('post');
+      expect(route.method).to.be.eq('POST');
     });
     });
 
 
     it('sets the option "path" to the "path" property', function () {
     it('sets the option "path" to the "path" property', function () {

+ 4 - 4
src/trie-router.d.ts

@@ -39,7 +39,7 @@ export declare class TrieRouter extends Service {
   defineRoute(routeDef: RouteDefinition): Route;
   defineRoute(routeDef: RouteDefinition): Route;
 
 
   /**
   /**
-   * Request handler.
+   * Request listener.
    *
    *
    * Example:
    * Example:
    * ```
    * ```
@@ -48,13 +48,13 @@ export declare class TrieRouter extends Service {
    *
    *
    * const router = new TrieRouter();
    * const router = new TrieRouter();
    * const server = new http.Server();
    * const server = new http.Server();
-   * server.on('request', router.requestHandler); // Sets the request handler.
-   * server.listen(3000);                         // Starts listening for connections.
+   * server.on('request', router.requestListener); // Sets the request listener.
+   * server.listen(3000);                          // Starts listening for connections.
    * ```
    * ```
    *
    *
    * @returns {Function}
    * @returns {Function}
    */
    */
-  get requestHandler(): RequestListener;
+  get requestListener(): RequestListener;
 
 
   /**
   /**
    * Add hook.
    * Add hook.

+ 4 - 4
src/trie-router.js

@@ -47,7 +47,7 @@ export class TrieRouter extends Service {
   }
   }
 
 
   /**
   /**
-   * Request handler.
+   * Request listener.
    *
    *
    * Example:
    * Example:
    * ```
    * ```
@@ -56,13 +56,13 @@ export class TrieRouter extends Service {
    *
    *
    * const router = new TrieRouter();
    * const router = new TrieRouter();
    * const server = new http.Server();
    * const server = new http.Server();
-   * server.on('request', router.requestHandler); // Sets the request handler.
-   * server.listen(3000);                         // Starts listening for connections.
+   * server.on('request', router.requestListener); // Sets the request listener.
+   * server.listen(3000);                          // Starts listening for connections.
    * ```
    * ```
    *
    *
    * @returns {Function}
    * @returns {Function}
    */
    */
-  get requestHandler() {
+  get requestListener() {
     return this._handleRequest.bind(this);
     return this._handleRequest.bind(this);
   }
   }
 
 

+ 20 - 20
src/trie-router.spec.js

@@ -25,10 +25,10 @@ describe('TrieRouter', function () {
     });
     });
   });
   });
 
 
-  describe('requestHandler', function () {
+  describe('requestListener', function () {
     it('to be a function', function () {
     it('to be a function', function () {
       const router = new TrieRouter();
       const router = new TrieRouter();
-      expect(typeof router.requestHandler).to.be.eq('function');
+      expect(typeof router.requestListener).to.be.eq('function');
     });
     });
 
 
     it('passes request context to the route handler', function (done) {
     it('passes request context to the route handler', function (done) {
@@ -43,7 +43,7 @@ describe('TrieRouter', function () {
       });
       });
       const req = createRequestMock({path: '/test'});
       const req = createRequestMock({path: '/test'});
       const res = createResponseMock();
       const res = createResponseMock();
-      router.requestHandler(req, res);
+      router.requestListener(req, res);
     });
     });
 
 
     it('passes path parameters to the request context', function (done) {
     it('passes path parameters to the request context', function (done) {
@@ -58,7 +58,7 @@ describe('TrieRouter', function () {
       });
       });
       const req = createRequestMock({path: '/foo-bar'});
       const req = createRequestMock({path: '/foo-bar'});
       const res = createResponseMock();
       const res = createResponseMock();
-      router.requestHandler(req, res);
+      router.requestListener(req, res);
     });
     });
 
 
     it('passes query parameters to the request context', function (done) {
     it('passes query parameters to the request context', function (done) {
@@ -73,7 +73,7 @@ describe('TrieRouter', function () {
       });
       });
       const req = createRequestMock({path: '?p1=foo&p2=bar'});
       const req = createRequestMock({path: '?p1=foo&p2=bar'});
       const res = createResponseMock();
       const res = createResponseMock();
-      router.requestHandler(req, res);
+      router.requestListener(req, res);
     });
     });
 
 
     it('passes parsed cookie to the request context', function (done) {
     it('passes parsed cookie to the request context', function (done) {
@@ -88,7 +88,7 @@ describe('TrieRouter', function () {
       });
       });
       const req = createRequestMock({headers: {cookie: 'p1=foo; p2=bar;'}});
       const req = createRequestMock({headers: {cookie: 'p1=foo; p2=bar;'}});
       const res = createResponseMock();
       const res = createResponseMock();
-      router.requestHandler(req, res);
+      router.requestListener(req, res);
     });
     });
 
 
     it('passes plain text body to the request context', function (done) {
     it('passes plain text body to the request context', function (done) {
@@ -104,7 +104,7 @@ describe('TrieRouter', function () {
       });
       });
       const req = createRequestMock({method: HTTP_METHOD.POST, body});
       const req = createRequestMock({method: HTTP_METHOD.POST, body});
       const res = createResponseMock();
       const res = createResponseMock();
-      router.requestHandler(req, res);
+      router.requestListener(req, res);
     });
     });
 
 
     it('passes parsed JSON body to the request context', function (done) {
     it('passes parsed JSON body to the request context', function (done) {
@@ -120,7 +120,7 @@ describe('TrieRouter', function () {
       });
       });
       const req = createRequestMock({method: HTTP_METHOD.POST, body: data});
       const req = createRequestMock({method: HTTP_METHOD.POST, body: data});
       const res = createResponseMock();
       const res = createResponseMock();
-      router.requestHandler(req, res);
+      router.requestListener(req, res);
     });
     });
 
 
     it('passes headers to the request context', function (done) {
     it('passes headers to the request context', function (done) {
@@ -138,7 +138,7 @@ describe('TrieRouter', function () {
       });
       });
       const req = createRequestMock({headers: {foo: 'bar'}});
       const req = createRequestMock({headers: {foo: 'bar'}});
       const res = createResponseMock();
       const res = createResponseMock();
-      router.requestHandler(req, res);
+      router.requestListener(req, res);
     });
     });
 
 
     it('uses DataSender to send the response', function (done) {
     it('uses DataSender to send the response', function (done) {
@@ -158,7 +158,7 @@ describe('TrieRouter', function () {
           done();
           done();
         },
         },
       });
       });
-      router.requestHandler(req, res);
+      router.requestListener(req, res);
     });
     });
 
 
     it('uses ErrorSender to send the response', function (done) {
     it('uses ErrorSender to send the response', function (done) {
@@ -181,7 +181,7 @@ describe('TrieRouter', function () {
           done();
           done();
         },
         },
       });
       });
-      router.requestHandler(req, res);
+      router.requestListener(req, res);
     });
     });
 
 
     describe('hooks', function () {
     describe('hooks', function () {
@@ -207,7 +207,7 @@ describe('TrieRouter', function () {
         });
         });
         const req = createRequestMock();
         const req = createRequestMock();
         const res = createResponseMock();
         const res = createResponseMock();
-        router.requestHandler(req, res);
+        router.requestListener(req, res);
         const result = await res.getBody();
         const result = await res.getBody();
         expect(result).to.be.eq(body);
         expect(result).to.be.eq(body);
         expect(order).to.be.eql(['preHandler1', 'preHandler2', 'handler']);
         expect(order).to.be.eql(['preHandler1', 'preHandler2', 'handler']);
@@ -235,7 +235,7 @@ describe('TrieRouter', function () {
         });
         });
         const req = createRequestMock();
         const req = createRequestMock();
         const res = createResponseMock();
         const res = createResponseMock();
-        router.requestHandler(req, res);
+        router.requestListener(req, res);
         const result = await res.getBody();
         const result = await res.getBody();
         expect(result).to.be.eq(body);
         expect(result).to.be.eq(body);
         expect(order).to.be.eql(['handler', 'postHandler1', 'postHandler2']);
         expect(order).to.be.eql(['handler', 'postHandler1', 'postHandler2']);
@@ -266,7 +266,7 @@ describe('TrieRouter', function () {
         });
         });
         const req = createRequestMock();
         const req = createRequestMock();
         const res = createResponseMock();
         const res = createResponseMock();
-        router.requestHandler(req, res);
+        router.requestListener(req, res);
         const result = await res.getBody();
         const result = await res.getBody();
         expect(result).to.be.eq(body);
         expect(result).to.be.eq(body);
         expect(order).to.be.eql(['preHandler1', 'preHandler2', 'handler']);
         expect(order).to.be.eql(['preHandler1', 'preHandler2', 'handler']);
@@ -301,7 +301,7 @@ describe('TrieRouter', function () {
         });
         });
         const req = createRequestMock();
         const req = createRequestMock();
         const res = createResponseMock();
         const res = createResponseMock();
-        router.requestHandler(req, res);
+        router.requestListener(req, res);
         const result = await res.getBody();
         const result = await res.getBody();
         expect(result).to.be.eq(body);
         expect(result).to.be.eq(body);
         expect(order).to.be.eql(['handler', 'postHandler1', 'postHandler2']);
         expect(order).to.be.eql(['handler', 'postHandler1', 'postHandler2']);
@@ -331,7 +331,7 @@ describe('TrieRouter', function () {
         });
         });
         const req = createRequestMock();
         const req = createRequestMock();
         const res = createResponseMock();
         const res = createResponseMock();
-        router.requestHandler(req, res);
+        router.requestListener(req, res);
         const result = await res.getBody();
         const result = await res.getBody();
         expect(result).to.be.eq(body);
         expect(result).to.be.eq(body);
         expect(order).to.be.eql(['preHandler1', 'preHandler2', 'handler']);
         expect(order).to.be.eql(['preHandler1', 'preHandler2', 'handler']);
@@ -361,7 +361,7 @@ describe('TrieRouter', function () {
         });
         });
         const req = createRequestMock();
         const req = createRequestMock();
         const res = createResponseMock();
         const res = createResponseMock();
-        router.requestHandler(req, res);
+        router.requestListener(req, res);
         const result = await res.getBody();
         const result = await res.getBody();
         expect(result).to.be.eq(body);
         expect(result).to.be.eq(body);
         expect(order).to.be.eql(['handler', 'postHandler1', 'postHandler2']);
         expect(order).to.be.eql(['handler', 'postHandler1', 'postHandler2']);
@@ -391,7 +391,7 @@ describe('TrieRouter', function () {
         });
         });
         const req = createRequestMock();
         const req = createRequestMock();
         const res = createResponseMock();
         const res = createResponseMock();
-        router.requestHandler(req, res);
+        router.requestListener(req, res);
         const result = await res.getBody();
         const result = await res.getBody();
         expect(result).to.be.eq(preHandlerBody);
         expect(result).to.be.eq(preHandlerBody);
         expect(result).not.to.be.eq(handlerBody);
         expect(result).not.to.be.eq(handlerBody);
@@ -421,7 +421,7 @@ describe('TrieRouter', function () {
         });
         });
         const req = createRequestMock();
         const req = createRequestMock();
         const res = createResponseMock();
         const res = createResponseMock();
-        router.requestHandler(req, res);
+        router.requestListener(req, res);
         const result = await res.getBody();
         const result = await res.getBody();
         expect(result).not.to.be.eq(handlerBody);
         expect(result).not.to.be.eq(handlerBody);
         expect(result).to.be.eq(postHandlerBody);
         expect(result).to.be.eq(postHandlerBody);
@@ -448,7 +448,7 @@ describe('TrieRouter', function () {
         });
         });
         const req = createRequestMock();
         const req = createRequestMock();
         const res = createResponseMock();
         const res = createResponseMock();
-        router.requestHandler(req, res);
+        router.requestListener(req, res);
         const result = await res.getBody();
         const result = await res.getBody();
         expect(result).to.be.eq(body);
         expect(result).to.be.eq(body);
         expect(order).to.be.eql(['preHandler', 'handler', 'postHandler']);
         expect(order).to.be.eql(['preHandler', 'handler', 'postHandler']);