add dingus reference to ctx
authorJustin Wind <justin.wind+git@gmail.com>
Sat, 5 Apr 2025 16:38:38 +0000 (09:38 -0700)
committerJustin Wind <justin.wind+git@gmail.com>
Sat, 5 Apr 2025 16:38:38 +0000 (09:38 -0700)
lib/dingus.js
test/lib/dingus.js

index 1e0c1a22abf909ef1e9555507c562fd653dc2827..08ebe86ec755df13c593afba0306bce422de3929 100644 (file)
@@ -82,6 +82,16 @@ class Dingus {
     ];
 
     this.logger = logger;
+
+    // Self reference added to each ctx.
+    const self = this;
+    this.selfProperty = {
+      get() {
+        return self;
+      },
+      configurable: false,
+      enumerable: false,
+    };
   }
 
 
@@ -536,6 +546,7 @@ class Dingus {
   async dispatch(req, res, ctx = {}) {
     const { handler, handlerArgs } = this._determineHandler(req, res, ctx);
     try {
+      Object.defineProperty(ctx, 'dingus', this.selfProperty);
       await this.preHandler(req, res, ctx);
       return await handler(req, res, ctx, ...handlerArgs);
     } catch (e) {
index 26f003cb8329b2a0622fde8b03012c012dd11da6..1f9266e76c658fa8eacae9901dcb964e3ce25496 100644 (file)
@@ -561,6 +561,22 @@ describe('Dingus', function () {
       assert(!dingus.handlerMethodNotAllowed.called);
       assert(!dingus.handlerNotFound.called);
     });
+    it('references dingus in ctx', async function () {
+      let result;
+      const urlPath = '/:id';
+      const method = 'GET';
+      const stubHandler = async (req, res, ctx) => {
+        result = ctx.dingus;
+      };
+      dingus.on(method, urlPath, stubHandler);
+      req.url = '/abc';
+      req.method = method;
+
+      await dingus.dispatch(req, res);
+      assert(!dingus.handlerMethodNotAllowed.called);
+      assert(!dingus.handlerNotFound.called);
+      assert.strictEqual(result, dingus);
+    });
     it('calls fallback handler', async function () {
       const urlPath = '/abc/:id';
       const method = 'GET';