Skip to content

Use with Node.js

In this guide, we’ll create several containers to manage dependencies and control the initialization order of services in a Node.js application.

Example

import { createContainer, compose } from '@grlt-hub/app-compose';
// Container for connecting to a database
const dbContainer = createContainer({
id: 'database',
start: async () => {
const dbConnection = await connectToDatabase();
console.log('Database connected');
return { api: { connection: dbConnection } };
},
enable: () => process.env.DB_ENABLE === 'true',
});
// Container for setting up cache
const cacheContainer = createContainer({
id: 'cache',
start: async () => {
const cache = await initializeCache();
console.log('Cache initialized');
return { api: { cache } };
},
enable: () => process.env.CACHE_ENABLE === 'true',
});
// Container for initializing an API service, which depends on the database and cache
const apiContainer = createContainer({
id: 'apiService',
dependsOn: [dbContainer, cacheContainer],
start: async (deps) => {
const api = await initializeApi({ db: deps.database.connection, cache: deps.cache.cache });
console.log('API service started');
return { api: { apiService: api } };
},
enable: () => true,
});
// Start all containers
async function startApp() {
try {
await compose.up([dbContainer, cacheContainer, apiContainer], { debug: true });
console.log('All services are up and running');
} catch (error) {
console.error('Error starting services:', error);
}
}
startApp();

Explanation

  • Database Container: Connects to the database only if DB_ENABLE is set to true. The database connection is provided as an API for other containers.
  • Cache Container: Initializes a cache system if CACHE_ENABLE is true. This is useful for enabling or disabling caching dynamically.
  • API Service Container: Depends on both the database and cache containers. It only starts after these dependencies are ready and has access to their APIs.

Conclusion

This example shows how to use app-compose to manage various services in a Node.js application, helping to control their initialization order and dependencies.