@launch77/database-dev
v0.2.0
Published
Development-time database infrastructure utilities for Launch77 apps (Docker, PostgreSQL, prompts, validation)
Downloads
100
Readme
@launch77/database-dev
Development-time database infrastructure utilities for Launch77 apps. This library provides tools for managing Docker containers, PostgreSQL databases, user prompts, and validation during development.
Note: This is a development-only library. Do not use in production code.
Features
- Docker Management - Port checking, container operations, health monitoring
- PostgreSQL Operations - Container lifecycle, connection testing, health checks
- User Prompts - Interactive confirmations and input collection
- Validation - Environment variables, dependencies, naming conventions
Installation
npm install --save-dev @launch77/database-devUsage
Docker Utilities
import {
checkPortAvailability,
isDockerRunning,
findContainerByName,
waitForContainerHealthy,
} from '@launch77/database-dev'
// Check if a port is available
const portCheck = await checkPortAvailability('5432')
if (!portCheck.available) {
console.log(`Port in use by: ${portCheck.usedBy}`)
console.log(`Project: ${portCheck.projectPath}`)
}
// Check if Docker is running
const dockerRunning = await isDockerRunning()
// Find a container
const container = await findContainerByName('my-postgres')
if (container) {
console.log(`Status: ${container.status}`)
}
// Wait for container to be healthy
await waitForContainerHealthy('my-postgres', 30, 1000)PostgreSQL Container Operations
import {
checkPostgresContainerExists,
startPostgresContainer,
waitForPostgresReady,
destroyPostgresContainer,
} from '@launch77/database-dev'
const composeFile = 'docker-compose.db.yml'
// Check if container exists
const exists = await checkPostgresContainerExists(composeFile)
// Start container
await startPostgresContainer(composeFile)
// Wait for database to be ready
await waitForPostgresReady(
'postgres://user:pass@localhost:5432/mydb',
60, // max attempts
1000 // interval ms
)
// Destroy container and volumes
await destroyPostgresContainer(composeFile)User Prompts
import { confirmAction, promptForInput, selectFromList } from '@launch77/database-dev'
// Confirm action
const confirmed = await confirmAction('Delete database?', false)
// Get user input
const name = await promptForInput('Database name:', 'default_db')
// Select from list
const option = await selectFromList(
'Choose environment:',
['development', 'staging', 'production'],
0 // default index
)Validation
import {
validateEnvironment,
validateDependencies,
validateConnectionString,
validateMigrationName,
} from '@launch77/database-dev'
// Validate environment variables
const envResult = validateEnvironment({
required: ['DATABASE_URL', 'API_KEY'],
optional: ['DEBUG'],
validateFormat: true,
})
if (!envResult.valid) {
console.error('Errors:', envResult.errors)
}
// Validate dependencies
const depResult = await validateDependencies(['docker', 'docker-compose'])
// Validate connection string
const connResult = validateConnectionString('postgres://user:pass@localhost:5432/mydb')
// Validate migration name
const validName = validateMigrationName('add_user_table') // true
const invalidName = validateMigrationName('Add User Table') // falseAPI Reference
Docker Utilities
checkPortAvailability(port)- Check if port is availableisDockerRunning()- Check if Docker daemon is runningfindContainerByName(name)- Find container by namegetContainerStatus(name)- Get container statusstartContainer(name)- Start a containerstopContainer(name)- Stop a containerremoveContainer(name, force?)- Remove a containerwaitForContainerHealthy(name, maxAttempts?, intervalMs?)- Wait for container healthexecInContainer(name, command)- Execute command in containergetContainerLogs(name, tail?)- Get container logs
PostgreSQL Container Utilities
checkPostgresContainerExists(composeFilePath)- Check if container existsstartPostgresContainer(composeFilePath)- Start PostgreSQL containerstopPostgresContainer(composeFilePath)- Stop PostgreSQL containerdestroyPostgresContainer(composeFilePath)- Destroy container and volumeswaitForPostgresReady(connectionString, maxAttempts?, intervalMs?)- Wait for databasetestPostgresConnection(connectionString)- Test database connectiongetPostgresVersion(connectionString)- Get PostgreSQL version
Prompt Utilities
confirmAction(question, defaultValue?)- Yes/no confirmationpromptForInput(question, defaultValue?)- Text inputselectFromList(question, options, defaultIndex?)- List selectionpromptForPassword(question)- Password input (note: not hidden in basic Node.js)
Validation Utilities
validateEnvironment(options)- Validate environment variablescheckCommandExists(command)- Check if command is availablevalidateDependencies(dependencies)- Validate required commandscheckPrerequisites()- Run all prerequisite checksvalidateMigrationName(name)- Validate migration name formatvalidateDatabaseName(name)- Validate database name formatvalidatePort(port)- Validate port numbervalidateConnectionString(connectionString)- Validate PostgreSQL connection string
Type Exports
import type {
PortCheckResult,
ContainerInfo,
PostgresContainerConfig,
PostgresConnectionError,
ValidationResult,
EnvironmentValidationOptions,
} from '@launch77/database-dev'Error Handling
All functions that interact with external systems (Docker, filesystem) can throw errors. Always wrap in try/catch:
try {
await startPostgresContainer('docker-compose.yml')
} catch (error) {
console.error('Failed to start container:', error.message)
}PostgreSQL connection functions provide classified errors:
try {
await waitForPostgresReady(connectionString)
} catch (error) {
if (error.isAuthError) {
console.error('Authentication failed')
} else if (error.isDatabaseMissingError) {
console.error('Database does not exist')
}
}Testing
All utilities include comprehensive unit tests. Run tests with:
npm testLicense
UNLICENSED - Internal Launch77 use only
