NestJS Backend Documentation - Decentralized Healthcare System Comprehensive documentation for the NestJS backend that interfaces with Stellar Soroban smart contracts for the decentralized healthcare management system.
- Architecture Overview
- Project Structure
- Installation & Setup
- Configuration
- Core Modules
- API Endpoints
- Database Schema
- Medical Records System
- Authentication & Authorization
- Stellar Integration
- Error Handling
- Testing
- Deployment
The NestJS backend serves as the application layer between the frontend and Stellar blockchain, providing:
- RESTful API endpoints for client applications
- Off-chain data caching and indexing
- User authentication and session management
- Encryption/decryption of sensitive health data
- Event listening and blockchain synchronization
- Business logic orchestration
- File upload and storage management
src/
├── main.ts # Application entry point
├── app.module.ts # Root application module
├── config/
│ └── database.config.ts # Database configuration
├── common/
│ └── filters/
│ └── http-exception.filter.ts # Global exception filter
└── medical-records/
├── medical-records.module.ts # Medical records module
├── entities/ # Database entities
│ ├── medical-record.entity.ts
│ ├── medical-record-version.entity.ts
│ ├── medical-history.entity.ts
│ ├── clinical-note-template.entity.ts
│ ├── medical-attachment.entity.ts
│ └── medical-record-consent.entity.ts
├── dto/ # Data Transfer Objects
│ ├── create-medical-record.dto.ts
│ ├── update-medical-record.dto.ts
│ ├── search-medical-records.dto.ts
│ ├── create-consent.dto.ts
│ └── create-clinical-template.dto.ts
├── services/ # Business logic services
│ ├── medical-records.service.ts
│ ├── clinical-templates.service.ts
│ ├── consent.service.ts
│ ├── file-upload.service.ts
│ └── reporting.service.ts
└── controllers/ # API controllers
├── medical-records.controller.ts
├── clinical-templates.controller.ts
├── consent.controller.ts
├── file-upload.controller.ts
└── reporting.controller.ts
- Node.js (v18 or higher)
- PostgreSQL (v12 or higher)
- npm or yarn
- Install dependencies:
npm install- Create a
.envfile from.env.example:
cp .env.example .env-
Update the
.envfile with your database credentials and configuration. -
Run database migrations (if using migrations):
npm run migration:run- Start the development server:
npm run start:devThe application will be available at http://localhost:3000
Swagger documentation will be available at http://localhost:3000/api
DB_HOST- Database host (default: localhost)DB_PORT- Database port (default: 5432)DB_USERNAME- Database username (default: postgres)DB_PASSWORD- Database password (default: postgres)DB_NAME- Database name (default: healthy_stellar)PORT- Application port (default: 3000)NODE_ENV- Environment (development/production)UPLOAD_PATH- File upload directory (default: ./storage/uploads)JWT_SECRET- JWT secret key for authenticationJWT_EXPIRES_IN- JWT expiration time
The medical records module provides comprehensive functionality for managing medical records, including:
- Medical record CRUD operations
- Version control and audit trails
- Clinical note templates
- Medical history and timeline tracking
- File attachments (images, documents)
- Consent management
- Search and reporting
POST /medical-records- Create a new medical recordGET /medical-records/search- Search medical recordsGET /medical-records/:id- Get a medical record by IDGET /medical-records/:id/versions- Get version historyGET /medical-records/timeline/:patientId- Get patient timelinePUT /medical-records/:id- Update a medical recordPUT /medical-records/:id/archive- Archive a medical recordPUT /medical-records/:id/restore- Restore an archived recordDELETE /medical-records/:id- Delete a medical record (soft delete)
POST /clinical-templates- Create a clinical templateGET /clinical-templates- Get all active templatesGET /clinical-templates/:id- Get a template by IDPUT /clinical-templates/:id- Update a templateDELETE /clinical-templates/:id- Delete a template
POST /consents- Create a new consentGET /consents/record/:recordId- Get consents for a recordGET /consents/patient/:patientId- Get consents for a patientGET /consents/check- Check if consent existsGET /consents/:id- Get a consent by IDPUT /consents/:id/revoke- Revoke a consent
POST /attachments/upload- Upload a file attachmentGET /attachments/record/:recordId- Get attachments for a recordGET /attachments/:id- Get an attachment by IDGET /attachments/:id/download- Download an attachmentDELETE /attachments/:id- Delete an attachment
GET /reports/patient/:patientId/summary- Get patient summaryGET /reports/activity- Get activity reportGET /reports/consent- Get consent reportGET /reports/statistics- Get statistics
The system uses the following main entities:
- MedicalRecord - Main medical record entity with version control
- MedicalRecordVersion - Version history for audit trails
- MedicalHistory - Timeline and activity tracking
- ClinicalNoteTemplate - Reusable clinical note templates
- MedicalAttachment - File attachments (images, documents)
- MedicalRecordConsent - Consent management and sharing
- Complete version history tracking
- Change tracking with before/after states
- Change reason documentation
- Automatic version numbering
- Reusable templates for common clinical notes
- Structured field definitions
- Template categorization
- System and custom templates
- Complete audit trail of all record activities
- Event types: created, updated, viewed, shared, archived, deleted
- IP address and user agent tracking
- Chronological timeline view
- Support for multiple file types (images, PDFs, documents)
- File size validation (10MB max)
- Secure file storage
- Metadata tracking
- Granular consent types (view, share, download, modify, delete)
- Consent expiration management
- Consent revocation with reason tracking
- Sharing with users and organizations
- Advanced search with filters
- Patient summary reports
- Activity reports
- Consent reports
- Statistical analysis
✅ Medical records maintain complete audit trails
- All changes are tracked in MedicalRecordVersion
- All activities are logged in MedicalHistory
- IP addresses and user agents are recorded
✅ Clinical documentation follows medical standards
- Structured templates for consistent documentation
- Version control ensures data integrity
- Metadata support for additional context
✅ Medical history is easily accessible and searchable
- Timeline endpoint for chronological view
- Search functionality with multiple filters
- Activity reports for analysis
✅ Patient consent is properly managed and documented
- Comprehensive consent entity with status tracking
- Expiration management
- Revocation with audit trail
- Consent verification endpoints
(To be implemented - placeholder for future authentication system)
(To be implemented - placeholder for Stellar Soroban smart contract integration)
The application uses a global exception filter (HttpExceptionFilter) that:
- Catches all exceptions
- Formats error responses consistently
- Logs errors appropriately
- Provides detailed error information in development
- Sanitizes error messages in production
The backend now includes an integrated clinical workflow surface across diagnosis, treatment planning, pharmacy, and documentation modules.
- Diagnosis and treatment planning integration:
- Get treatment plans by diagnosis
- Get patient diagnoses with linked treatment plans
- Validate diagnosis IDs on treatment plan create/update
- Prescription and medication workflow improvements:
- Search prescriptions by status/patient/prescriber/date
- Update eligible prescriptions
- Add and retrieve prescription note history
- Clinical documentation enhancements:
- Dedicated
clinical-notesendpoints - SOAP/progress/discharge/consultation note support
- Note completeness checks and signing workflow
- Dedicated
- Procedure/care tracking and decision support:
- Procedure cancellation endpoint
- Auto decision-support alerts on treatment/procedure lifecycle changes
- Treatment plan progress endpoint for care coordination dashboards
GET /diagnosis/:id/treatment-plansGET /diagnosis/patient/:patientId/treatment-plansGET /treatment-plans(search filters)GET /treatment-plans/:id/progressGET /pharmacy/prescriptions(search filters)PATCH /pharmacy/prescriptions/:idPOST /pharmacy/prescriptions/:id/notesGET /pharmacy/prescriptions/:id/notesPOST /clinical-notesGET /clinical-notesPOST /clinical-notes/:id/signGET /clinical-notes/:id/completeness
# Unit tests
npm run test
# E2E tests
npm run test:e2e
# Test coverage
npm run test:covnpm run build
npm run start:prod- Set
NODE_ENV=production - Configure proper database credentials
- Set up secure file storage
- Configure CORS appropriately
- Enable HTTPS
- Set up proper logging and monitoring
MIT