Skip to content

Commit cdb0244

Browse files
committed
add defineConfig/loadConfig to pgkit package
1 parent 2253b99 commit cdb0244

File tree

4 files changed

+129
-20
lines changed

4 files changed

+129
-20
lines changed

packages/pgkit/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"vitest": "^1.2.2"
3333
},
3434
"dependencies": {
35-
"@pgkit/client": "workspace:^"
35+
"@pgkit/client": "workspace:^",
36+
"importx": "^0.4.4"
3637
}
3738
}

packages/pgkit/src/config.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import * as fs from 'fs'
2+
import * as path from 'path'
3+
4+
export type Config = {
5+
client: {
6+
connectionString: string
7+
}
8+
typegen?: {
9+
connectionString?: string
10+
}
11+
migrator?: {
12+
connectionString?: string
13+
/** @default '${cwd}/migrations' */
14+
migrationsTableName?: string
15+
/** @default 'migrations' */
16+
migrationsPath?: string
17+
}
18+
}
19+
20+
export const defineConfig = (config: Config) => config
21+
22+
export const loadConfig = async () => {
23+
const importx = await import('importx')
24+
const configLocations = ['pgkit.config.ts', 'pgkit.config.js']
25+
let config: Config | undefined
26+
let cwd = process.cwd()
27+
while (!config) {
28+
for (const configLocation of configLocations) {
29+
const filepath = path.join(cwd, configLocation)
30+
if (fs.existsSync(filepath)) {
31+
config = await importx.import(filepath, {
32+
parentURL: new URL(`file://${cwd}`),
33+
})
34+
if ((config as {default?: Config}).default) {
35+
config = (config as {default?: Config}).default
36+
}
37+
if (!config) {
38+
throw new Error(`Config file ${filepath} doesn't export a valid config object.`)
39+
}
40+
break
41+
}
42+
}
43+
cwd = path.dirname(cwd)
44+
}
45+
46+
if (!config) {
47+
throw new Error(`No config file found. Try creating one at ${path.join(cwd, configLocations[0])}`)
48+
}
49+
50+
return config
51+
}

pgkit.config.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export default {
2+
client: {
3+
connectionString: 'postgresql://postgres:postgres@localhost:5432/postgres',
4+
},
5+
} satisfies import('./packages/pgkit/src/config').Config

pnpm-lock.yaml

Lines changed: 71 additions & 19 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)