This repo demos connections to a single postgresql database from multiple servers.
This package contains the shared database functionality for the Authenticate application.
The @database/database package provides a unified database interface for all services in the Authenticate application. It handles connections, migrations, and provides a consistent API for database operations.
This package is designed to be consumed by other services within the Authenticate monorepo. It is not published to npm, but instead is referenced locally.
To use this package in another service:
{
"dependencies": {
"@database/database": "file:../database"
}
}This package uses the "prepare" script to automatically build TypeScript code when the package is installed. This ensures that any service using this package will have access to the compiled JavaScript and TypeScript declarations without needing to build it manually.
The package is automatically built when:
- The package is installed via npm
- Any service that depends on it runs
npm install
The build process compiles TypeScript source files to JavaScript in the dist directory.
import { getDataSource, closeDatabase } from '@database/database';
// Example: Connect to the database
async function connectToDatabase() {
const dataSource = await getDataSource();
// Use the dataSource for database operations
// When done, close the connection
await closeDatabase();
}getDataSource(): Returns a TypeORM DataSource instancecloseDatabase(): Closes the database connection
# Start docker components
docker-compose down -v && docker-compose up -d
# Comfirm database is running
docker exec -it database-app-postgres-1 psql -U app_user -d app_db
# Confirm hydra logs
docker logs --tail 20 database-service-name
# Start backend
npm run dev # npm run start:dev - for initialization
# Start server
npm run dev # npm run start:dev - for initialization# Run all pending migrations
npm run migration:run
# Generate a new migration based on entity changes
npm run migration:generate -- MigrationName
# Create a new empty migration
npm run migration:create# Run seed scripts
npm run seed
# Reset database (run migrations and seeds)
npm run reset# Run tests
npm test
# Run tests in watch mode
npm run test:watchThis package uses:
- TypeORM for database ORM
- PostgreSQL as the primary database
- Redis for caching (if applicable)
If you encounter issues importing from this package, ensure:
- The package has been built (
distdirectory exists) - The service using this package has the correct reference in package.json
- TypeScript paths are correctly configured in the consuming service
When making changes to this package:
- Ensure backward compatibility when possible
- Create migrations for any schema changes
- Update tests to reflect changes
- Increment version number according to semver