Skip to content

Commit

Permalink
feat: allow to nest domains
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Jan 10, 2020
1 parent 056d8f0 commit 4b4fdf0
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 8 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Intercepts stdout/ stderr.

## Implementation

This module uses [`domain`](https://nodejs.org/api/domain.html) to capture asyncrhonous function output.
This module uses [`domain`](https://nodejs.org/api/domain.html) to capture asynchronous function output.

Read [Capturing stdout/ stderr in Node.js using Domain module](https://medium.com/@gajus/capturing-stdout-stderr-in-node-js-using-domain-module-3c86f5b1536d).

Expand Down
8 changes: 5 additions & 3 deletions src/factories/createOutputInterceptor.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ export default (userConfiguration?: OutputInterceptorUserConfigurationType): Out
}

const interceptor = async (routine) => {
if (process.domain) {
throw new Error('Cannot intercept output within an exiting domain context.');
}
const parentDomain: any = process.domain;

const domain: any = createDomain();

Expand Down Expand Up @@ -81,6 +79,10 @@ export default (userConfiguration?: OutputInterceptorUserConfigurationType): Out

interceptor.output = output;

if (parentDomain && parentDomain.outputInterceptor) {
parentDomain.outputInterceptor.output += output;
}

if (routineError) {
throw routineError;
}
Expand Down
15 changes: 11 additions & 4 deletions test/output-interceptor/factories/createOutputInterceptor.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,20 +167,27 @@ test('works as expected when multiple interceptors are constructed simultaneousl
t.is(intercept.output, 'foo\n');
});

test('throws an error if an attempt is made to use output-interceptor within an existing domain', async (t) => {
test('captures nested output-interceptor output', async (t) => {
const intercept1 = createOutputInterceptor();
const intercept2 = createOutputInterceptor();

const error = await t.throwsAsync(intercept1(async () => {
let output0;

await intercept1(async () => {
console.log('foo');

// eslint-disable-next-line require-await
await intercept2(async () => {
console.log('bar');
});

output0 = intercept2.output;

console.log('baz');
}));
});

const output1 = intercept1.output;

t.is(error.message, 'Cannot intercept output within an exiting domain context.');
t.is(output0, 'bar\n');
t.is(output1, 'foo\nbar\nbaz\n');
});

0 comments on commit 4b4fdf0

Please sign in to comment.