diff --git a/README.md b/README.md index a19bd09..705020d 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,26 @@ export default function doWork () { } ``` +## `.enterWith()` + +In case `.runInAsyncScope()` is incovenient, you can use `.enterWith()` + +```js +import fastify from 'fastify' +import asyncforge from 'fastify-asyncforge' + +const fastify = Fastify() + +// Calling .enterWith() is necessary or `asyncforge.app()` will throw +fastify.enterWith() +asyncforge.app() +``` + +### Notice + +Note that you cannot wrap `.enterWith()` inside an async function, as it will not work. +If you are interested in knowing more, read https://github.com/nodejs/node/issues/53037. + ## License MIT diff --git a/index.js b/index.js index db8a2e1..7414333 100644 --- a/index.js +++ b/index.js @@ -18,6 +18,13 @@ const fastifyAsyncForge = fp(function (fastify, opts, next) { }) }) + fastify.decorate('enterWith', function () { + const store = create() + store.enterWith() + app.set(this) + logger.set(this.log) + }) + fastify.addHook('onRequest', function (req, res, next) { const store = create() diff --git a/test/before.test.js b/test/before.test.js new file mode 100644 index 0000000..b232a06 --- /dev/null +++ b/test/before.test.js @@ -0,0 +1,41 @@ +'use strict' + +const { describe, it, before } = require('node:test') +const assert = require('node:assert') +const Fastify = require('fastify') +const asyncforge = require('../') + +describe('support exiting from a context', () => { + let fastify + before(async () => { + fastify = Fastify() + await fastify.register(asyncforge) + }) + + it('throws', () => { + assert.throws(asyncforge.app) + }) + + it('does not throw using enterWith', () => { + fastify.enterWith() + assert.equal(asyncforge.app(), fastify) + }) +}) + +describe('enterWith in before', () => { + let fastify + before(async () => { + fastify = Fastify() + await fastify.register(asyncforge) + fastify.enterWith() + }) + + it('throws', () => { + assert.throws(asyncforge.app) + }) + + it('does not throw using enterWith again', () => { + fastify.enterWith() + assert.equal(asyncforge.app(), fastify) + }) +})