alexmarqs / zod-config

Load configuration variables from multiple sources with flexible adapters, ensuring type safety with Zod.
https://www.npmjs.com/package/zod-config
MIT License
34 stars 7 forks source link

Avoiding top-level await (with Drizzle ORM) #2

Open sz3lbi opened 8 months ago

sz3lbi commented 8 months ago

I would like to use this package in a project that uses Drizzle ORM.

I want to configure migrations, so I need to configure the database connection.
Here's what it should look like according to the Drizzle ORM docs:

import 'dotenv/config';
import type { Config } from 'drizzle-kit';

export default {
  schema: './src/schema.ts',
  out: './drizzle',
  driver: 'mysql2', // 'pg' | 'mysql2' | 'better-sqlite' | 'libsql' | 'turso'
  dbCredentials: {
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
  },
} satisfies Config;

(https://orm.drizzle.team/docs/migrations)

However, Node.js doesn't allow for top-level awaits that your tool returns when using loadConfig (in my case with dotenv).

const customConfig = await loadConfig({
  schema: schemaConfig,
  adapters: dotEnvAdapter({ 
    path: filePath,
    prefixKey: 'MY_APP_',
  }),
});

Any tips on how to make it work?

PS. I was looking for a tool that would allow me to have a really type safe env variables in my application and this looks like a good fit. Thanks for creating it.

alexmarqs commented 8 months ago

Hi @sz3lbi , thanks for reaching out! If your setup does not allow top level await (non esm projects) I believe it's not possible unless drizzle allows async configuration load in some way. In fact from the drizzle repo issues, there are a few requests in that direction: https://github.com/drizzle-team/drizzle-orm/issues/1187.

The idea of this tool was mainly to have an async behaviour so we could have adapters to load configurations from external sources. With dotenv package is possible because of its sync behaviour. What you are asking would be possible in this tool if I provide a loadConfigSync where we only have/allow sync adapters (in fact the built in adapters that i provide can be like that). I will consider this for the next release! ;)