Adapters
Adapters are components responsible for handling I/O processes and external integrations. They serve as the bridge between your business logic and external systems such as databases, APIs, file systems, or cache stores.
Purpose
Adapters abstract away the implementation details of external dependencies, allowing:
Interchangeability - Easily swap implementations (e.g., PostgreSQL → MongoDB)
Testability - Mock external dependencies in tests
Isolation - Keep business logic independent of infrastructure concerns
Location
All adapter components MUST be placed under the src/adapters directory in the project.
src/
└── adapters/
├── database/
├── storage/
├── cache/
└── external-api/Shared Interfaces
Adapters SHOULD be built with interchangeability in mind. Define shared interfaces in src/types.ts so that multiple adapters can implement the same contract.
Example: Storage Interface
Memory Storage Adapter
Here's a simple in-memory storage adapter implementation, useful for testing or development.
Directory Structure
Implementation: component.ts
component.tsRedis Storage Adapter
Here's a production-ready Redis adapter that demonstrates lifecycle management.
Implementation: component.ts
component.tsError Handling: errors.ts
errors.tsDatabase Adapter Example
Here's an example of a PostgreSQL database adapter.
Lifecycle Methods
WKC provides special lifecycle methods that are automatically called:
[Lifecycle.ComponentStarted]or[START_COMPONENT]- Called when the service starts[Lifecycle.ComponentStopped]or[STOP_COMPONENT]- Called when the service shuts down
When to Use Lifecycle Methods
Use lifecycle methods when your adapter needs to:
Establish connections (database, cache, message queue)
Initialize pools or clients
Perform health checks
Clean up resources on shutdown
Close connections gracefully
Best Practices
1. Error Handling
Always handle connection errors and throw meaningful custom errors:
2. Configuration
Use the config component to manage adapter settings:
3. Logging
Log important operations for debugging and monitoring:
4. Type Safety
Always type your return values properly:
5. Resource Management
Always clean up resources in the stop lifecycle method:
Testing Adapters
See the Testing Services (WKC) documentation for detailed guidance on testing adapters.
Quick Example
Last updated