2.5 KiB
2.5 KiB
Awilix DI Container Migration Guide
This guide explains how to use the new Awilix dependency injection container in the data-ingestion service.
Overview
The Awilix container provides proper dependency injection for decoupled libraries, allowing them to be reused in other projects without stock-bot specific dependencies.
Current Implementation
The data-ingestion service now uses a hybrid approach:
- Awilix container for ProxyManager and other decoupled services
- Legacy service factory for backward compatibility
Usage Example
// Create Awilix container
const awilixConfig = {
redis: {
host: config.database.dragonfly.host,
port: config.database.dragonfly.port,
db: config.database.dragonfly.db,
},
mongodb: {
uri: config.database.mongodb.uri,
database: config.database.mongodb.database,
},
postgres: {
host: config.database.postgres.host,
port: config.database.postgres.port,
database: config.database.postgres.database,
user: config.database.postgres.user,
password: config.database.postgres.password,
},
proxy: {
cachePrefix: 'proxy:',
ttl: 3600,
},
};
const container = createServiceContainer(awilixConfig);
await initializeServices(container);
// Access services from container
const proxyManager = container.resolve('proxyManager');
const cache = container.resolve('cache');
Handler Integration
Handlers receive services through the enhanced service container:
// Create service adapter with proxy from Awilix
const serviceContainerWithProxy = createServiceAdapter(services);
Object.defineProperty(serviceContainerWithProxy, 'proxy', {
get: () => container.resolve('proxyManager'),
enumerable: true,
configurable: true
});
// Handlers can now access proxy service
class MyHandler extends BaseHandler {
async myOperation() {
const proxy = this.proxy.getRandomProxy();
// Use proxy...
}
}
Benefits
- Decoupled Libraries: Libraries no longer depend on @stock-bot/config
- Reusability: Libraries can be used in other projects
- Testability: Easy to mock dependencies for testing
- Type Safety: Full TypeScript support with Awilix
Next Steps
To fully migrate to Awilix:
- Update HTTP library to accept dependencies via constructor
- Update Queue library to accept Redis config via constructor
- Create actual MongoDB, PostgreSQL, and QuestDB clients in the container
- Remove legacy service factory once all services are migrated