UNPKG

arangojs

Version:

The official ArangoDB JavaScript driver.

81 lines • 2.93 kB
/** * Transaction ID scope for opt-in asynchronous stream transaction steps. * * @packageDocumentation * @internal */ let nodeAsyncLocalStorage = null; let nodeAsyncLocalStorageReady = null; let nodeAsyncLocalStorageError; const browserTransactionIds = new WeakMap(); function isNodeRuntime() { return (typeof process !== "undefined" && typeof process.versions === "object" && process.versions !== null && typeof process.versions.node === "string"); } function ensureNodeAsyncLocalStorage() { if (!isNodeRuntime() || nodeAsyncLocalStorage) { return Promise.resolve(); } if (!nodeAsyncLocalStorageReady) { nodeAsyncLocalStorageReady = (async () => { try { // Keep the specifier dynamic so browser bundlers do not try to resolve // the Node-only module. const specifier = ["node:", "async_hooks"].join(""); const { AsyncLocalStorage } = (await import(specifier)); nodeAsyncLocalStorage = new AsyncLocalStorage(); } catch (error) { nodeAsyncLocalStorageError = error; } })(); } return nodeAsyncLocalStorageReady; } /** * Returns the transaction ID scoped to `connection`, if any. */ export function getActiveTransactionId(connection) { const context = nodeAsyncLocalStorage?.getStore(); if (context?.connection === connection) { return context.transactionId; } return browserTransactionIds.get(connection); } /** * Runs `callback` with `transactionId` scoped to `connection` until the * callback's returned Promise settles. */ export async function runTransactionStep(connection, transactionId, callback) { await ensureNodeAsyncLocalStorage(); const invoke = () => { const promise = callback(); if (!promise || typeof promise.then !== "function") { throw new Error("Transaction callback was not an async function or did not return a promise!"); } return Promise.resolve(promise); }; if (isNodeRuntime()) { if (!nodeAsyncLocalStorage) { const detail = nodeAsyncLocalStorageError instanceof Error ? `: ${nodeAsyncLocalStorageError.message}` : ""; throw new Error(`Async transaction context is unavailable in this Node.js runtime${detail}`); } return nodeAsyncLocalStorage.run({ connection, transactionId }, invoke); } if (browserTransactionIds.has(connection)) { throw new Error("Concurrent asynchronous transaction steps on the same connection are not supported in browsers."); } browserTransactionIds.set(connection, transactionId); try { return await invoke(); } finally { browserTransactionIds.delete(connection); } } //# sourceMappingURL=transaction-context.js.map