Skip to content

Commit

Permalink
feat(node): allow overriding AsyncHook, AsyncLocalStorage and `As…
Browse files Browse the repository at this point in the history
…yncResource` with `globalThis` (#126)
  • Loading branch information
pi0 authored Aug 8, 2023
1 parent ae04a73 commit 9141c15
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
5 changes: 4 additions & 1 deletion src/runtime/node/async_hooks/_async-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type asyncHooks from "node:async_hooks";

// https://nodejs.org/api/async_hooks.html

export class AsyncHook implements asyncHooks.HookCallbacks {
class _AsyncHook implements asyncHooks.HookCallbacks {
readonly __unenv__ = true;

_enabled: boolean = false;
Expand Down Expand Up @@ -53,6 +53,9 @@ export class AsyncHook implements asyncHooks.HookCallbacks {
}
}

export const AsyncHook: asyncHooks.AsyncHook =
(globalThis as any).AsyncHook || _AsyncHook;

export const createHook: typeof asyncHooks.createHook = function createHook(
callbacks,
) {
Expand Down
5 changes: 4 additions & 1 deletion src/runtime/node/async_hooks/_async-local-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type asyncHooks from "node:async_hooks";

// https://nodejs.org/api/async_context.html#class-asynclocalstorage

export class AsyncLocalStorage<T> implements asyncHooks.AsyncLocalStorage<T> {
class _AsyncLocalStorage<T> implements asyncHooks.AsyncLocalStorage<T> {
readonly __unenv__ = true;

_currentStore: undefined | T;
Expand Down Expand Up @@ -51,3 +51,6 @@ export class AsyncLocalStorage<T> implements asyncHooks.AsyncLocalStorage<T> {
throw new Error("[unenv] `AsyncLocalStorage.snapshot` is not implemented!");
}
}

export const AsyncLocalStorage: typeof asyncHooks.AsyncLocalStorage =
(globalThis as any).AsyncLocalStorage || _AsyncLocalStorage;
5 changes: 4 additions & 1 deletion src/runtime/node/async_hooks/_async-resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { executionAsyncId } from "./_async-hook";

let _asyncIdCounter = 100;

export class AsyncResource implements asyncHooks.AsyncResource {
class _AsyncResource implements asyncHooks.AsyncResource {
readonly __unenv__ = true;

type: string;
Expand Down Expand Up @@ -63,3 +63,6 @@ export class AsyncResource implements asyncHooks.AsyncResource {
return this._triggerAsyncId as number;
}
}

export const AsyncResource: typeof asyncHooks.AsyncResource =
(globalThis as any).AsyncResource || _AsyncResource;

0 comments on commit 9141c15

Please sign in to comment.