Skip to content

Instantly share code, notes, and snippets.

@jordiup
Created August 29, 2024 14:45
Show Gist options
  • Save jordiup/a2e93cff573bc8a94d062283a61e844c to your computer and use it in GitHub Desktop.
Save jordiup/a2e93cff573bc8a94d062283a61e844c to your computer and use it in GitHub Desktop.
Zod Postgres Connection Schema
import { z } from 'zod';
const connectionSchema = z.object({
user: z.string(),
password: z.string(),
host: z.string(),
database: z.string(),
port: z.number().int().positive().default(5432),
ssl: z.boolean().default(true),
pooling: z.boolean().default(true),
additionalParamString: z.string().optional(),
// Make url optional, as we can generate it from other fields
url: z.string().url().optional(),
});
export type Connection = z.infer<typeof connectionSchema>;
export { connectionSchema };
export function generateConnectionString(connection: Connection): string {
const {
user,
password,
host,
database,
port,
ssl,
pooling,
additionalParamString,
} = connection;
let connectionString = `postgres://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${database}`;
const params: string[] = [];
if (ssl) {
params.push('sslmode=require');
}
if (pooling) {
params.push('pgbouncer=true');
}
if (additionalParamString) {
params.push(additionalParamString);
}
if (params.length > 0) {
connectionString += `?${params.join('&')}`;
}
return connectionString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment