From: Justin Wind Date: Sat, 5 Apr 2025 16:38:38 +0000 (-0700) Subject: add dingus reference to ctx X-Git-Url: https://git.squeep.com/?a=commitdiff_plain;h=refs%2Fheads%2Fv2.2-dev;p=squeep-api-dingus add dingus reference to ctx --- 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';