diff --git a/index.js b/index.js index 315583c..db8a2e1 100644 --- a/index.js +++ b/index.js @@ -9,10 +9,13 @@ const reply = memo('fastify.reply') const logger = memo('fastify.logger') const fastifyAsyncForge = fp(function (fastify, opts, next) { - const store = create() - fastify.decorate('runInAsyncScope', function (fn) { - return store.run(fn) + const store = create() + return store.run(() => { + app.set(this) + logger.set(this.log) + return fn() + }) }) fastify.addHook('onRequest', function (req, res, next) { @@ -28,7 +31,7 @@ const fastifyAsyncForge = fp(function (fastify, opts, next) { }) }) - store.run(() => { + create(() => { app.set(fastify) logger.set(fastify.log) next() diff --git a/test/basic.test.js b/test/basic.test.js index 8c9d1b1..e3b3352 100644 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -36,14 +36,49 @@ test('basic helpers', async (t) => { await p.completed }) -test('basic helpers without start', async (t) => { +test('support in following plugin', async (t) => { const p = tspl(t, { plan: 7 }) const fastify = Fastify() + fastify.register(fastifyAsyncForge) + + fastify.register(async function (fastify, _opts) { + p.strictEqual(app(), Object.getPrototypeOf(fastify)) + p.strictEqual(request(), undefined) + }) + + fastify.get('/', async function (_request, _reply) { + p.strictEqual(app(), this) + p.strictEqual(request(), _request) + p.strictEqual(reply(), _reply) + p.strictEqual(logger(), _request.log) + return { hello: 'world' } + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + + p.strictEqual(res.statusCode, 200) + + await p.completed +}) + +test('support in following plugin with await ', async (t) => { + const p = tspl(t, { plan: 9 }) + const fastify = Fastify() + await fastify.register(fastifyAsyncForge) - p.throws(logger) - p.throws(app) + fastify.register(async function (fastify, _opts) { + p.throws(app) + p.throws(request) + fastify.runInAsyncScope(() => { + p.strictEqual(app(), fastify) + p.strictEqual(request(), undefined) + }) + }) fastify.get('/', async function (_request, _reply) { p.strictEqual(app(), this) @@ -148,3 +183,32 @@ test('onRequest hook added before registration fails', async (t) => { await p.completed }) + +test('basic helpers with start', async (t) => { + const p = tspl(t, { plan: 7 }) + const fastify = Fastify() + + await fastify.register(fastifyAsyncForge) + + fastify.runInAsyncScope(() => { + p.strictEqual(logger(), fastify.log) + p.strictEqual(app(), fastify) + }) + + fastify.get('/', async function (_request, _reply) { + p.strictEqual(app(), this) + p.strictEqual(request(), _request) + p.strictEqual(reply(), _reply) + p.strictEqual(logger(), _request.log) + return { hello: 'world' } + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + + p.strictEqual(res.statusCode, 200) + + await p.completed +})