@modern-js/runtime-utils
Version:
A Progressive React Framework for modern web development.
34 lines (33 loc) • 1.24 kB
JavaScript
import "node:module";
import { AsyncLocalStorage } from "async_hooks";
const createStorage = ()=>{
let storage;
if (void 0 !== AsyncLocalStorage) storage = new AsyncLocalStorage();
const run = (context, cb)=>{
if (!storage) throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
`);
return new Promise((resolve, reject)=>{
storage.run(context, ()=>{
try {
return resolve(cb());
} catch (error) {
return reject(error);
}
});
});
};
const useContext = ()=>{
if (!storage) throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
`);
const context = storage?.getStore();
if (!context) throw new Error("Can't call useContext out of scope, make sure @modern-js/runtime-utils is a single version in node_modules");
return context;
};
return {
run,
useContext
};
};
const async_storage_server_storage = createStorage();
const getAsyncLocalStorage = async ()=>async_storage_server_storage;
export { getAsyncLocalStorage, async_storage_server_storage as storage };