In Next.js (v.15 w/ App Router) i have 2 modules of server actions where i export the same functions, each with a different database, like so :
–> databases/mongodb/server_actions
...all the necessary imports, "use server" declaration, etc
export interface IActionState {
success: string | null
error: string | null
}
const createWallet = async (
previousState: IActionState,
formData: FormData
): Promise<IActionState> => {
try {
const session = await auth()
await connectDB()
const title = formData.get("title") as string
const user = session?.user?.email as string
const wallet = new WalletModel({ title, user })
await wallet.save()
//await new Promise((resolve) => setTimeout(resolve, 1000)) // Simulate slow network
return { success: `Wallet ${title} created successfully`, error: null }
} catch (error: any) {
//await new Promise((resolve) => setTimeout(resolve, 1000)) // Simulate slow network
return { success: null, error: error?.message || "An error occurred" }
}
}
export {
createWallet,
//and some others
}
the other one is databases/postgres/server_actions
with the same logic
How can i create a third module, which only responsibility would be to determine which one to expose to the consumer component ?
I have tried something like :
–> dbActionsRouter.ts
const DATABASE = process.env.NEXT_PUBLIC_DATABASE
let moduleToExport: any
if (DATABASE === "MONGODB") {
moduleToExport = await import("@/databases/mongodb/server_actions")
} else if (DATABASE === "POSTGRES") {
moduleToExport = await import("@/databases/postgres/server_actions")
} else {
throw new Error("DATABASE environment variable is not set or is invalid")
}
console.log(`Using ${DATABASE} database`)
console.log(`Using ${moduleToExport} as database actions`)
export default moduleToExport
But when i try to import it at a client component
import { createWallet } from "@/dbActionsRouter"
i get
module ‘”@/dbActionsRouter”‘ has no exported member ‘createWallet’
and after running it at :
...
<form action={action}>
...
Unhandled Runtime Error
TypeError: action is not a function
and these 2 console warnings :
./app/create_wallet/NewWalletForm.client.tsx
Attempted import error: ‘createWallet’ is not exported from ‘@/dbActionsRouter’ (imported as ‘createWallet’).
and
./dbActionsRouter.ts
The generated code contains ‘async/await’ because this module is using “topLevelAwait”.
However, your target environment does not appear to support ‘async/await’.
As a result, the code may not run as expected or may cause runtime errors.
Also is this the correct way to have multiple databases ready to be used ?
Im trying to make it as simple and readable as possible instead of checking the env variable at every action and run the operation in a different db every time
3