From 8c12c2c32a8362572d856478f212b311678abf19 Mon Sep 17 00:00:00 2001 From: Justin Wind Date: Sat, 5 Apr 2025 09:38:38 -0700 Subject: [PATCH] add dingus reference to ctx --- lib/dingus.js | 11 +++++++++++ test/lib/dingus.js | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/dingus.js b/lib/dingus.js index 1e0c1a2..08ebe86 100644 --- a/lib/dingus.js +++ b/lib/dingus.js @@ -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) { diff --git a/test/lib/dingus.js b/test/lib/dingus.js index 26f003c..1f9266e 100644 --- a/test/lib/dingus.js +++ b/test/lib/dingus.js @@ -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'; -- 2.49.0