Browse Source

refactor: replaces hardcoded root path with its constant

e22m4u 3 weeks ago
parent
commit
8a7a38c5cb

+ 7 - 7
dist/cjs/index.cjs

@@ -186,7 +186,7 @@ __name(isResponseSent, "isResponseSent");
 function createRouteMock(options = {}) {
   return new Route({
     method: options.method || HttpMethod.GET,
-    path: options.path || "/",
+    path: options.path || ROOT_PATH,
     handler: options.handler || (() => "OK")
   });
 }
@@ -474,7 +474,7 @@ function createRequestMock(patch) {
     }
   }
   const request = patch.stream || createRequestStream(patch.secure, patch.body, patch.encoding);
-  request.url = createRequestUrl(patch.path || "/", patch.query);
+  request.url = createRequestUrl(patch.path || ROOT_PATH, patch.query);
   request.headers = createRequestHeaders(
     patch.host,
     patch.secure,
@@ -526,7 +526,7 @@ function createRequestUrl(path, query) {
       query
     );
   }
-  let url = ("/" + path).replace("//", "/");
+  let url = (ROOT_PATH + path).replace("//", "/");
   if (typeof query === "object") {
     const qs = import_querystring.default.stringify(query);
     if (qs) {
@@ -728,7 +728,7 @@ function getRequestPathname(request) {
       request
     );
   }
-  return (request.url || "/").replace(/\?.*$/, "");
+  return (request.url || ROOT_PATH).replace(/\?.*$/, "");
 }
 __name(getRequestPathname, "getRequestPathname");
 
@@ -1457,14 +1457,14 @@ var _RouteRegistry = class _RouteRegistry extends DebuggableService {
    */
   matchRouteByRequest(request) {
     const debug = this.getDebuggerFor(this.matchRouteByRequest);
-    const requestPath = (request.url || "/").replace(/\?.*$/, "");
+    const requestPath = getRequestPathname(request);
     debug(
       "Matching routes with the request %s %v.",
       request.method.toUpperCase(),
       requestPath
     );
     const rawTriePath = `${request.method.toUpperCase()}/${requestPath}`;
-    const triePath = rawTriePath.replace(/\/+/g, "/");
+    const triePath = rawTriePath.replace(/\/+/g, ROOT_PATH);
     const resolved = this._trie.match(triePath);
     if (resolved) {
       const route = resolved.value;
@@ -1886,7 +1886,7 @@ var _TrieRouter = class _TrieRouter extends DebuggableService {
    */
   async _handleRequest(request, response) {
     const debug = this.getDebuggerFor(this._handleRequest);
-    const requestPath = (request.url || "/").replace(/\?.*$/, "");
+    const requestPath = getRequestPathname(request);
     debug(
       "Preparing to handle an incoming request %s %v.",
       request.method,

+ 15 - 15
src/hooks/hook-invoker.spec.js

@@ -1,8 +1,8 @@
 import {expect} from 'chai';
 import {format} from '@e22m4u/js-format';
 import {HookInvoker} from './hook-invoker.js';
-import {Route, HttpMethod} from '../route/index.js';
 import {createResponseMock} from '../utils/index.js';
+import {Route, HttpMethod, ROOT_PATH} from '../route/index.js';
 import {HookRegistry, RouterHookType} from './hook-registry.js';
 
 describe('HookInvoker', function () {
@@ -36,7 +36,7 @@ describe('HookInvoker', function () {
       throwable(
         new Route({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           handler: () => undefined,
         }),
       )();
@@ -46,7 +46,7 @@ describe('HookInvoker', function () {
       const s = new HookInvoker();
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler: () => undefined,
       });
       const res = createResponseMock();
@@ -75,7 +75,7 @@ describe('HookInvoker', function () {
       const s = new HookInvoker();
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler: () => undefined,
       });
       const res = createResponseMock();
@@ -91,7 +91,7 @@ describe('HookInvoker', function () {
       const s = new HookInvoker();
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler: () => undefined,
       });
       const throwable = v => () =>
@@ -131,7 +131,7 @@ describe('HookInvoker', function () {
       });
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           () => {
             order.push('routeHook1');
@@ -171,7 +171,7 @@ describe('HookInvoker', function () {
       });
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           () => {
             order.push('routeHook1');
@@ -203,7 +203,7 @@ describe('HookInvoker', function () {
       });
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           () => {
             order.push('routeHook1');
@@ -241,7 +241,7 @@ describe('HookInvoker', function () {
       });
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           () => {
             throw new Error('Should not be called');
@@ -273,7 +273,7 @@ describe('HookInvoker', function () {
       });
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           () => {
             order.push('routeHook1');
@@ -305,7 +305,7 @@ describe('HookInvoker', function () {
       });
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           () => {
             order.push('routeHook1');
@@ -351,7 +351,7 @@ describe('HookInvoker', function () {
       });
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           () => {
             order.push('routeHook1');
@@ -395,7 +395,7 @@ describe('HookInvoker', function () {
       );
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           () => {
             order.push('routeHook1');
@@ -432,7 +432,7 @@ describe('HookInvoker', function () {
       });
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           () => {
             order.push('routeHook1');
@@ -473,7 +473,7 @@ describe('HookInvoker', function () {
       });
       const route = new Route({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         preHandler: [
           async () => {
             order.push('routeHook1');

+ 4 - 3
src/route-registry.js

@@ -1,5 +1,6 @@
-import {Route} from './route/index.js';
 import {PathTrie} from '@e22m4u/js-path-trie';
+import {ROOT_PATH, Route} from './route/index.js';
+import {getRequestPathname} from './utils/index.js';
 import {ServiceContainer} from '@e22m4u/js-service';
 import {InvalidArgumentError} from '@e22m4u/js-format';
 import {DebuggableService} from './debuggable-service.js';
@@ -58,7 +59,7 @@ export class RouteRegistry extends DebuggableService {
    */
   matchRouteByRequest(request) {
     const debug = this.getDebuggerFor(this.matchRouteByRequest);
-    const requestPath = (request.url || '/').replace(/\?.*$/, '');
+    const requestPath = getRequestPathname(request);
     debug(
       'Matching routes with the request %s %v.',
       request.method.toUpperCase(),
@@ -67,7 +68,7 @@ export class RouteRegistry extends DebuggableService {
     const rawTriePath = `${request.method.toUpperCase()}/${requestPath}`;
     // маршрут формируется с удалением дубликатов косой черты
     // "OPTIONS//api/users/login" => "OPTIONS/api/users/login"
-    const triePath = rawTriePath.replace(/\/+/g, '/');
+    const triePath = rawTriePath.replace(/\/+/g, ROOT_PATH);
     const resolved = this._trie.match(triePath);
     if (resolved) {
       const route = resolved.value;

+ 2 - 2
src/trie-router.js

@@ -5,8 +5,8 @@ import {ServiceContainer} from '@e22m4u/js-service';
 import {ServerResponse, IncomingMessage} from 'http';
 import {DebuggableService} from './debuggable-service.js';
 import {DataSender, ErrorSender} from './senders/index.js';
-import {isPromise, isResponseSent} from './utils/index.js';
 import {HookInvoker, HookRegistry, RouterHookType} from './hooks/index.js';
+import {isPromise, isResponseSent, getRequestPathname} from './utils/index.js';
 
 /**
  * Trie router.
@@ -74,7 +74,7 @@ export class TrieRouter extends DebuggableService {
    */
   async _handleRequest(request, response) {
     const debug = this.getDebuggerFor(this._handleRequest);
-    const requestPath = (request.url || '/').replace(/\?.*$/, '');
+    const requestPath = getRequestPathname(request);
     debug(
       'Preparing to handle an incoming request %s %v.',
       request.method,

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

@@ -1,10 +1,10 @@
 import {expect} from 'chai';
 import {TrieRouter} from './trie-router.js';
-import {Route, HttpMethod} from './route/index.js';
 import {RequestContext} from './request-context.js';
 import {ServerResponse, IncomingMessage} from 'http';
 import {DataSender, ErrorSender} from './senders/index.js';
 import {HookRegistry, RouterHookType} from './hooks/index.js';
+import {Route, HttpMethod, ROOT_PATH} from './route/index.js';
 import {createRequestMock, createResponseMock} from './utils/index.js';
 
 describe('TrieRouter', function () {
@@ -61,7 +61,7 @@ describe('TrieRouter', function () {
       const router = new TrieRouter();
       router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler: ({query}) => {
           expect(query).to.be.eql({p1: 'foo', p2: 'bar'});
           done();
@@ -76,7 +76,7 @@ describe('TrieRouter', function () {
       const router = new TrieRouter();
       router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler: ({cookies}) => {
           expect(cookies).to.be.eql({p1: 'foo', p2: 'bar'});
           done();
@@ -92,7 +92,7 @@ describe('TrieRouter', function () {
       const body = 'Lorem Ipsum is simply dummy text.';
       router.defineRoute({
         method: HttpMethod.POST,
-        path: '/',
+        path: ROOT_PATH,
         handler: ctx => {
           expect(ctx.body).to.be.eq(body);
           done();
@@ -108,7 +108,7 @@ describe('TrieRouter', function () {
       const data = {p1: 'foo', p2: 'bar'};
       router.defineRoute({
         method: HttpMethod.POST,
-        path: '/',
+        path: ROOT_PATH,
         handler: ({body}) => {
           expect(body).to.be.eql(data);
           done();
@@ -123,7 +123,7 @@ describe('TrieRouter', function () {
       const router = new TrieRouter();
       router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler: ({headers}) => {
           expect(headers).to.be.eql({
             host: 'localhost',
@@ -142,7 +142,7 @@ describe('TrieRouter', function () {
       const metaData = {foo: {bar: {baz: 'qux'}}};
       const currentRoute = router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         meta: metaData,
         handler: ({route}) => {
           expect(route).to.be.eq(currentRoute);
@@ -159,7 +159,7 @@ describe('TrieRouter', function () {
       const metaData = {role: 'admin'};
       router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         meta: metaData,
         handler: ({meta}) => {
           expect(meta).to.eql(metaData);
@@ -176,7 +176,7 @@ describe('TrieRouter', function () {
       const resBody = 'Lorem Ipsum is simply dummy text.';
       router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler: () => resBody,
       });
       const req = createRequestMock();
@@ -196,7 +196,7 @@ describe('TrieRouter', function () {
       const error = new Error();
       router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler: () => {
           throw error;
         },
@@ -221,7 +221,7 @@ describe('TrieRouter', function () {
         const body = 'OK';
         router.defineRoute({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           preHandler: [
             () => {
               order.push('preHandler1');
@@ -249,7 +249,7 @@ describe('TrieRouter', function () {
         const body = 'OK';
         router.defineRoute({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           handler: () => {
             order.push('handler');
             return body;
@@ -277,7 +277,7 @@ describe('TrieRouter', function () {
         const body = 'OK';
         router.defineRoute({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           preHandler: [
             ctx => {
               order.push('preHandler1');
@@ -309,7 +309,7 @@ describe('TrieRouter', function () {
         let requestContext;
         router.defineRoute({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           handler: ctx => {
             order.push('handler');
             expect(ctx).to.be.instanceof(RequestContext);
@@ -343,7 +343,7 @@ describe('TrieRouter', function () {
         const body = 'OK';
         router.defineRoute({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           preHandler: [
             () => {
               order.push('preHandler1');
@@ -373,7 +373,7 @@ describe('TrieRouter', function () {
         const body = 'OK';
         router.defineRoute({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           handler: () => {
             order.push('handler');
             return body;
@@ -405,7 +405,7 @@ describe('TrieRouter', function () {
         const postHandlerBody = 'baz';
         router.defineRoute({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           preHandler() {
             order.push('preHandler');
             return preHandlerBody;
@@ -436,7 +436,7 @@ describe('TrieRouter', function () {
         const postHandlerBody = 'bar';
         router.defineRoute({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           preHandler() {
             order.push('preHandler');
           },
@@ -464,7 +464,7 @@ describe('TrieRouter', function () {
         const body = 'OK';
         router.defineRoute({
           method: HttpMethod.GET,
-          path: '/',
+          path: ROOT_PATH,
           preHandler() {
             order.push('preHandler');
           },
@@ -491,7 +491,7 @@ describe('TrieRouter', function () {
       const router = new TrieRouter();
       router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler(ctx) {
           const res = ctx.container.getRegistered(RequestContext);
           expect(res).to.be.eq(ctx);
@@ -510,7 +510,7 @@ describe('TrieRouter', function () {
       const res = createResponseMock();
       router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler(ctx) {
           const result = ctx.container.getRegistered(IncomingMessage);
           expect(result).to.be.eq(req);
@@ -526,7 +526,7 @@ describe('TrieRouter', function () {
       const res = createResponseMock();
       router.defineRoute({
         method: HttpMethod.GET,
-        path: '/',
+        path: ROOT_PATH,
         handler(ctx) {
           const result = ctx.container.getRegistered(ServerResponse);
           expect(result).to.be.eq(res);
@@ -540,7 +540,7 @@ describe('TrieRouter', function () {
       const router = new TrieRouter();
       router.defineRoute({
         method: HttpMethod.POST,
-        path: '/',
+        path: ROOT_PATH,
         handler() {},
       });
       const req = createRequestMock({
@@ -563,8 +563,8 @@ describe('TrieRouter', function () {
       let handlerCalled = false;
       const router = new TrieRouter();
       router.defineRoute({
-        method: 'GET',
-        path: '/',
+        method: HttpMethod.GET,
+        path: ROOT_PATH,
         preHandler(ctx) {
           return new Promise(resolve => {
             setTimeout(() => {
@@ -579,7 +579,7 @@ describe('TrieRouter', function () {
           return 'Response from main handler';
         },
       });
-      const req = createRequestMock({method: 'GET', path: '/'});
+      const req = createRequestMock({method: HttpMethod.GET, path: ROOT_PATH});
       const res = createResponseMock();
       await router._handleRequest(req, res);
       const responseBody = await res.getBody();

+ 3 - 2
src/utils/create-request-mock.js

@@ -2,6 +2,7 @@ import {Socket} from 'net';
 import {TLSSocket} from 'tls';
 import {IncomingMessage} from 'http';
 import queryString from 'querystring';
+import {ROOT_PATH} from '../route/index.js';
 import {InvalidArgumentError} from '@e22m4u/js-format';
 import {isReadableStream} from './is-readable-stream.js';
 import {createCookieString} from './create-cookie-string.js';
@@ -149,7 +150,7 @@ export function createRequestMock(patch) {
   const request =
     patch.stream ||
     createRequestStream(patch.secure, patch.body, patch.encoding);
-  request.url = createRequestUrl(patch.path || '/', patch.query);
+  request.url = createRequestUrl(patch.path || ROOT_PATH, patch.query);
   request.headers = createRequestHeaders(
     patch.host,
     patch.secure,
@@ -228,7 +229,7 @@ function createRequestUrl(path, query) {
       query,
     );
   }
-  let url = ('/' + path).replace('//', '/');
+  let url = (ROOT_PATH + path).replace('//', '/');
   if (typeof query === 'object') {
     const qs = queryString.stringify(query);
     if (qs) {

+ 3 - 2
src/utils/create-request-mock.spec.js

@@ -3,6 +3,7 @@ import {Stream} from 'stream';
 import {TLSSocket} from 'tls';
 import {expect} from 'chai';
 import {format} from '@e22m4u/js-format';
+import {ROOT_PATH} from '../route/index.js';
 import {createRequestMock} from './create-request-mock.js';
 import {CHARACTER_ENCODING_LIST} from './fetch-request-body.js';
 
@@ -271,7 +272,7 @@ describe('createRequestMock', function () {
 
   it('uses the default path "/" without a query string', function () {
     const req = createRequestMock();
-    expect(req.url).to.be.eq('/');
+    expect(req.url).to.be.eq(ROOT_PATH);
   });
 
   it('uses by default only the "host" header', function () {
@@ -379,7 +380,7 @@ describe('createRequestMock', function () {
 
   it('the parameter "host" does not affect the url', async function () {
     const req = createRequestMock({host: 'myHost'});
-    expect(req.url).to.be.eq('/');
+    expect(req.url).to.be.eq(ROOT_PATH);
     expect(req.headers['host']).to.be.eq('myHost');
   });
 

+ 2 - 2
src/utils/create-route-mock.js

@@ -1,4 +1,4 @@
-import {Route, HttpMethod} from '../route/index.js';
+import {Route, HttpMethod, ROOT_PATH} from '../route/index.js';
 
 /**
  * @typedef {object} RouteMockOptions
@@ -16,7 +16,7 @@ import {Route, HttpMethod} from '../route/index.js';
 export function createRouteMock(options = {}) {
   return new Route({
     method: options.method || HttpMethod.GET,
-    path: options.path || '/',
+    path: options.path || ROOT_PATH,
     handler: options.handler || (() => 'OK'),
   });
 }

+ 2 - 2
src/utils/create-route-mock.spec.js

@@ -1,13 +1,13 @@
 import {expect} from 'chai';
-import {HttpMethod, Route} from '../route/index.js';
 import {createRouteMock} from './create-route-mock.js';
+import {HttpMethod, ROOT_PATH, Route} from '../route/index.js';
 
 describe('createRouteMock', function () {
   it('returns an instance of Route with default options', function () {
     const res = createRouteMock();
     expect(res).to.be.instanceof(Route);
     expect(res.method).to.be.eq(HttpMethod.GET);
-    expect(res.path).to.be.eq('/');
+    expect(res.path).to.be.eq(ROOT_PATH);
     expect(res.handler()).to.be.eq('OK');
   });
 

+ 2 - 1
src/utils/get-request-pathname.js

@@ -1,3 +1,4 @@
+import {ROOT_PATH} from '../route/index.js';
 import {InvalidArgumentError} from '@e22m4u/js-format';
 
 /**
@@ -19,5 +20,5 @@ export function getRequestPathname(request) {
       request,
     );
   }
-  return (request.url || '/').replace(/\?.*$/, '');
+  return (request.url || ROOT_PATH).replace(/\?.*$/, '');
 }