oscklm
oscklm7mo ago

Multiple actions in one file, using different node modules?

Hey, So i currently have a actions.ts holding my actions. In that i have multiple actions, and import some different modules at the top.
const client = new Mux({
tokenId: process.env.MUX_TOKEN_ID,
tokenSecret: process.env.MUX_TOKEN_SECRET,
});
const client = new Mux({
tokenId: process.env.MUX_TOKEN_ID,
tokenSecret: process.env.MUX_TOKEN_SECRET,
});
When i need to create a client like above, should i create these clients in the top of actions.ts or inside of the invidual actions? I would think that creating them inside the action, unless they are shared makes sense. Are there any docs or something that can better help outline the "life cycle" of an action and how it works when having multiple in one file. I'm very curious to better understand how this actually get "compiled" into runnable code?
2 Replies
lee
lee7mo ago
great question! tl;dr personally i would create shared clients in the global scope, but you can do either. it shouldn't matter for performance or behavior. It's mostly a code cleanliness thing. action lifecycle: when you npx convex dev: Convex runs the files to find the list of exported functions, but doesn't run any of the actions/queries/mutations. This is called "analyze time". Basically it runs imports, anything that runs in the global scope, and the wrappers like action() but not the action handler. then when you call an action: first Convex loads the file, at "import time", which is identical to analyze time except that env variables like process.env.MUX_TOKEN_ID may have changed since the code was pushed. Note this doesn't need to happen every time; we have plans to cache state after import time, in which case doing initialization at global scope would be slightly more efficient, but that work is in-progress. Now that the environment is set up, Convex calls the action handler. Within the handler, you can do custom setup for that one action, including await imports to load more code dynamically. And that's it.
oscklm
oscklmOP7mo ago
Awesome insight @lee thanks!

Did you find this page helpful?