Skip to content

Commit 2579e12

Browse files
authored
feat: create schema automatically (#96)
1 parent c9dac92 commit 2579e12

File tree

2 files changed

+24
-16
lines changed

2 files changed

+24
-16
lines changed

src/server.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import { Server, IncomingMessage, ServerResponse } from 'http'
33
import { runMigrations } from './utils/migrate'
44
import { createServer } from './app'
55
import pino from 'pino'
6+
import { getConfig } from './utils/config'
7+
import { Client } from 'pg'
8+
9+
const config = getConfig()
610

711
const logger = pino({
812
formatters: {
@@ -23,8 +27,24 @@ const main = async () => {
2327
// Init config
2428
const port = process.env.PORT || 8080
2529

30+
// Init DB
31+
const dbConfig = {
32+
connectionString: config.DATABASE_URL,
33+
connectionTimeoutMillis: 10_000,
34+
}
35+
const client = new Client(dbConfig)
36+
2637
// Run migrations
27-
await runMigrations()
38+
try {
39+
await client.connect()
40+
41+
// Ensure schema exists, not doing it via migration to not break current migration checksums
42+
await client.query(`CREATE SCHEMA IF NOT EXISTS ${config.SCHEMA};`)
43+
44+
await runMigrations(client)
45+
} finally {
46+
await client.end()
47+
}
2848

2949
// Start the server
3050
app.listen({ port: Number(port), host: '0.0.0.0' }, (err, address) => {

src/utils/migrate.ts

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,44 +5,32 @@ import fs from 'node:fs'
55

66
const config = getConfig()
77

8-
async function connectAndMigrate(
9-
databaseUrl: string | undefined,
10-
migrationsDirectory: string,
11-
logOnError = false
12-
) {
8+
async function connectAndMigrate(client: Client, migrationsDirectory: string, logOnError = false) {
139
if (!fs.existsSync(migrationsDirectory)) {
1410
console.log(`Migrations directory ${migrationsDirectory} not found, skipping`)
1511
return
1612
}
1713

18-
const dbConfig = {
19-
connectionString: databaseUrl,
20-
connectionTimeoutMillis: 10_000,
21-
}
2214
const optionalConfig = {
2315
schemaName: config.SCHEMA,
2416
tableName: 'migrations',
2517
}
2618

27-
const client = new Client(dbConfig)
2819
try {
29-
await client.connect()
3020
await migrate({ client }, migrationsDirectory, optionalConfig)
3121
} catch (error) {
3222
if (logOnError && error instanceof Error) {
3323
console.error('Migration error:', error.message)
3424
} else {
3525
throw error
3626
}
37-
} finally {
38-
await client.end()
3927
}
4028
}
4129

42-
export async function runMigrations(): Promise<void> {
30+
export async function runMigrations(client: Client): Promise<void> {
4331
try {
4432
console.log('Running migrations')
45-
await connectAndMigrate(config.DATABASE_URL, './db/migrations')
33+
await connectAndMigrate(client, './db/migrations')
4634
} catch (error) {
4735
throw error
4836
} finally {

0 commit comments

Comments
 (0)