import { registerAs } from '@nestjs/config'; import { ConnectionString } from 'connection-string'; import { first } from 'lodash'; import { z } from 'zod'; export const databaseSchema = z.object({ connectionString: z.string(), type: z.enum([ 'mysql', 'postgres', 'cockroachdb', 'sap', 'mariadb', 'sqlite', 'cordova', 'react-native', 'nativescript', 'sqljs', 'oracle', 'mssql', 'mongodb', 'aurora-mysql', 'aurora-postgres', 'expo', 'better-sqlite3', 'capacitor', 'spanner', ]), host: z.string(), port: z.number().optional(), username: z.string(), password: z.string(), database: z.string(), secure: z.boolean(), }); export type DatabaseConfig = z.TypeOf; export const rawDatabaseSchema = z.object({ connectionString: z.string(), secure: z.boolean().default(true), }); export type RawDatabaseConfigSchema = z.TypeOf; export const databaseConfigFactory = (opts: RawDatabaseConfigSchema) => registerAs('database', () => { const connectionString = new ConnectionString(opts.connectionString); const config: DatabaseConfig = databaseSchema.strict().parse({ connectionString: connectionString.toString(), type: connectionString.protocol, host: first(connectionString.hosts)?.name, port: first(connectionString.hosts)?.port, username: connectionString.user, password: connectionString.password, database: first(connectionString.path), secure: opts.secure, }); return config; });