Skip to content

Commit

Permalink
add defineConfig/loadConfig to pgkit package
Browse files Browse the repository at this point in the history
  • Loading branch information
mmkal committed Sep 16, 2024
1 parent 2253b99 commit cdb0244
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 20 deletions.
3 changes: 2 additions & 1 deletion packages/pgkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"vitest": "^1.2.2"
},
"dependencies": {
"@pgkit/client": "workspace:^"
"@pgkit/client": "workspace:^",
"importx": "^0.4.4"
}
}
51 changes: 51 additions & 0 deletions packages/pgkit/src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import * as fs from 'fs'
import * as path from 'path'

export type Config = {
client: {
connectionString: string
}
typegen?: {
connectionString?: string
}
migrator?: {
connectionString?: string
/** @default '${cwd}/migrations' */
migrationsTableName?: string
/** @default 'migrations' */
migrationsPath?: string
}
}

export const defineConfig = (config: Config) => config

export const loadConfig = async () => {
const importx = await import('importx')
const configLocations = ['pgkit.config.ts', 'pgkit.config.js']
let config: Config | undefined
let cwd = process.cwd()
while (!config) {
for (const configLocation of configLocations) {
const filepath = path.join(cwd, configLocation)
if (fs.existsSync(filepath)) {
config = await importx.import(filepath, {
parentURL: new URL(`file://${cwd}`),
})
if ((config as {default?: Config}).default) {
config = (config as {default?: Config}).default
}
if (!config) {
throw new Error(`Config file ${filepath} doesn't export a valid config object.`)
}
break
}
}
cwd = path.dirname(cwd)
}

if (!config) {
throw new Error(`No config file found. Try creating one at ${path.join(cwd, configLocations[0])}`)
}

return config
}
5 changes: 5 additions & 0 deletions pgkit.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
client: {
connectionString: 'postgresql://postgres:postgres@localhost:5432/postgres',
},
} satisfies import('./packages/pgkit/src/config').Config
90 changes: 71 additions & 19 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit cdb0244

Please sign in to comment.