...

/

Solution: Dynamically Load a Database Client Using ES Modules

Solution: Dynamically Load a Database Client Using ES Modules

Use a path map and dynamic import() to load the correct client module and return an instance—without using conditionals.

We'll cover the following...

Solution explanation

  • Lines 1–4: We define a pathMap object that maps environment names ('dev''prod') to module paths ('./sqlite.js''./postgres.js').

    • This replaces conditional logic with a clean lookup table for selecting modules dynamically.

  • Lines 6–11: We implement createDbClient(env) as an asynchronous factory.

    • It retrieves the correct ...