feat: add env and config-file sources
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { parseConnections } from './store.js'
|
||||
import type { ConnectionConfig } from './types.js'
|
||||
|
||||
export const readEnvConnections = (env: NodeJS.ProcessEnv = process.env): ConnectionConfig[] => {
|
||||
const raw = env.DBMOLE_CONNECTIONS
|
||||
if (!raw) {
|
||||
return []
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(raw)
|
||||
} catch {
|
||||
console.error('dbmole: DBMOLE_CONNECTIONS is not valid JSON, ignoring')
|
||||
return []
|
||||
}
|
||||
if (!Array.isArray(parsed)) {
|
||||
console.error('dbmole: DBMOLE_CONNECTIONS must be a JSON array, ignoring')
|
||||
return []
|
||||
}
|
||||
return parseConnections(parsed, 'env DBMOLE_CONNECTIONS')
|
||||
}
|
||||
|
||||
export const readConfigFile = (path: string | undefined): ConnectionConfig[] => {
|
||||
if (!path) {
|
||||
return []
|
||||
}
|
||||
if (!existsSync(path)) {
|
||||
console.error('dbmole: config file ' + path + ' not found, ignoring')
|
||||
return []
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'))
|
||||
} catch {
|
||||
console.error('dbmole: config file ' + path + ' is not valid JSON, ignoring')
|
||||
return []
|
||||
}
|
||||
const connections = (parsed as { connections?: unknown }).connections
|
||||
if (!Array.isArray(connections)) {
|
||||
console.error(
|
||||
'dbmole: config file ' + path + ' must contain { "connections": [...] }, ignoring'
|
||||
)
|
||||
return []
|
||||
}
|
||||
return parseConnections(connections, 'config ' + path)
|
||||
}
|
||||
Reference in New Issue
Block a user