### Initialize and Bootstrap Artus Application Source: https://context7.com/artusjs/core/llms.txt Demonstrates how to create an Artus application instance, load modules using a manifest, and execute lifecycle hooks. It includes setting environment configurations and accessing application properties like config and logger. ```typescript import 'reflect-metadata'; import path from 'path'; import { ArtusApplication } from '@artus/core'; // Create application instance const app = new ArtusApplication({ containerName: 'myApp', env: ['dev'] // or ['prod', 'test'] }); // Load application with manifest await app.load({ version: '2', refMap: { _app: { pluginConfig: {}, items: [ { path: path.resolve(__dirname, './lifecycle'), extname: '.ts', filename: 'lifecycle.ts', loader: 'lifecycle-hook-unit', source: 'app', }, { path: path.resolve(__dirname, './controllers/hello'), extname: '.ts', filename: 'hello.ts', loader: 'module', source: 'app', } ] } } }, __dirname); // Run application lifecycle hooks await app.run(); // Emits willReady and didReady hooks // Access application services console.log(app.config); // Merged configuration console.log(app.logger); // Logger instance // Graceful shutdown await app.close(); ``` -------------------------------- ### Manage Configuration with Automatic Merging (TypeScript) Source: https://context7.com/artusjs/core/llms.txt Demonstrates how to manage environment-specific configuration files that are automatically merged based on the application's environment. This includes default configurations and environment-specific overrides. ```typescript import { ConfigurationHandler } from '@artus/core'; // config/config.default.ts export default { server: { port: 3000, host: '127.0.0.1' }, database: { host: 'localhost', port: 5432 } }; // config/config.dev.ts export default { database: { database: 'artus_dev', logging: true } }; // config/config.prod.ts export default { server: { port: 8080 }, database: { database: 'artus_prod', logging: false } }; // Configuration is automatically merged based on env const app = new ArtusApplication({ env: ['prod'] }); await app.load(manifest, root); console.log(app.config); // Output: { // server: { port: 8080, host: '127.0.0.1' }, // database: { host: 'localhost', port: 5432, database: 'artus_prod', logging: false } // } // Access configuration handler directly const configHandler = app.configurationHandler; configHandler.setConfig('custom', { feature: { enabled: true } }); const merged = configHandler.getMergedConfig(); ``` -------------------------------- ### Artus Dependency Injection: Services and Controllers Source: https://context7.com/artusjs/core/llms.txt Illustrates how to define and register services and controllers using decorators like `@Injectable` and `@Inject`. This facilitates dependency resolution within the Artus application container. It shows singleton and execution scope management. ```typescript import 'reflect-metadata'; import { Inject, Injectable, ScopeEnum } from '@artus/injection'; @Injectable({ scope: ScopeEnum.SINGLETON }) export class HelloService { getGreeting(): string { return 'Hello from Artus'; } getTestHeaders(): Record { return { 'x-hello-artus': 'true' }; } } @Injectable({ scope: ScopeEnum.EXECUTION // New instance per request }) export class HelloController { @Inject(HelloService) helloService: HelloService; async index() { return { status: 200, content: this.helloService.getGreeting(), headers: this.helloService.getTestHeaders() }; } } // Access from application container const controller = app.container.get(HelloController); const result = await controller.index(); console.log(result); // { status: 200, content: 'Hello from Artus', headers: {...} } ``` -------------------------------- ### Scan Project Directories for Module Manifests (TypeScript) Source: https://context7.com/artusjs/core/llms.txt Scans project directories to generate manifest files for module loading. This involves configuring the ArtusScanner with options like output file path, scanning policies, file extensions, and exclusions. It outputs a manifest object detailing module references and their configurations. Dependencies include '@artus/core' and 'path'. ```typescript import { ArtusScanner, ScanPolicy } from '@artus/core'; import path from 'path'; // Create scanner with options const scanner = new ArtusScanner({ needWriteFile: true, // Write manifest.json manifestFilePath: './manifest.json', useRelativePath: true, configDir: 'config', policy: ScanPolicy.All, // Scan all directories extensions: ['.ts', '.js'], // File extensions to scan exclude: ['node_modules', 'test', 'coverage'], envs: ['dev', 'prod'], plugin: { 'my-plugin': { enable: true, path: path.resolve(__dirname, './plugins/my-plugin') } } }); // Scan project root const manifest = await scanner.scan(path.resolve(__dirname)); console.log(manifest); // Output: { // version: '2', // refMap: { // _app: { // pluginConfig: { ... }, // items: [ // { path: './src/controller/user', loader: 'module', ... }, // { path: './src/service/user', loader: 'module', ... }, // { path: './src/lifecycle', loader: 'lifecycle-hook-unit', ... } // ] // } // } // } // Use ScanPolicy for different scanning strategies const appOnlyScanner = new ArtusScanner({ policy: ScanPolicy.AppOnly, // Only scan app directory needWriteFile: false }); ``` -------------------------------- ### Standardized Exception Handling with Localization (TypeScript) Source: https://context7.com/artusjs/core/llms.txt Explains how to define and throw standardized exceptions using `ArtusStdError`, including support for localization of error messages and detailed URLs. It also shows how to use application helper methods for throwing and creating exceptions. ```typescript import { ArtusStdError, ExceptionItem } from '@artus/core'; // Register exception codes ArtusStdError.registerCode('INVALID_USER', { desc: { en: 'User validation failed', zh: '用户验证失败' }, detailUrl: 'https://docs.example.com/errors/invalid-user' }); ArtusStdError.registerCode('DATABASE_ERROR', { desc: 'Database connection failed', detailUrl: 'https://docs.example.com/errors/database' }); // Set locale ArtusStdError.setCurrentLocale('en'); // Throw exception try { const error = new ArtusStdError('INVALID_USER'); throw error; } catch (err) { if (err instanceof ArtusStdError) { console.log(err.code); // 'INVALID_USER' console.log(err.desc); // 'User validation failed' console.log(err.detailUrl); // 'https://docs.example.com/errors/invalid-user' console.log(err.message); // '[INVALID_USER] User validation failed, Please check on https://docs.example.com/errors/invalid-user' } } // Using app helper methods app.throwException('DATABASE_ERROR'); // Throws immediately const error = app.createException('DATABASE_ERROR'); // Creates without throwing ``` -------------------------------- ### Utilize Built-in Logger with Different Levels (TypeScript) Source: https://context7.com/artusjs/core/llms.txt Demonstrates how to use the application's built-in logger, which is automatically available via `app.logger`. It supports various log levels such as `info`, `debug`, `warn`, `error`, `fatal`, and `trace`. Custom loggers can also be instantiated with specific log level configurations. The logger can be injected into services using `@Inject(Logger)`. Dependencies include '@artus/core'. ```typescript import { Logger, LoggerLevel } from '@artus/core'; // Logger is automatically available in app app.logger.info('Application started'); app.logger.debug('Debug information'); app.logger.warn('Warning message'); app.logger.error('Error occurred', new Error('Something failed')); app.logger.fatal('Fatal error', new Error('Critical failure')); app.logger.trace('Trace information'); // Create custom logger const customLogger = new Logger({ level: LoggerLevel.WARN }); customLogger.info('This will not be logged'); // Below WARN level customLogger.warn('This will be logged'); // Use in plugins or services @Injectable() export class MyService { @Inject(Logger) logger: Logger; async doWork() { this.logger.info('Starting work'); try { // ... work } catch (err) { this.logger.error('Work failed', err); throw err; } } } ``` -------------------------------- ### Artus Lifecycle Hooks Implementation Source: https://context7.com/artusjs/core/llms.txt Shows how to implement various lifecycle hooks within an Artus application using decorators like `@LifecycleHookUnit` and `@LifecycleHook`. It covers hooks for configuration loading, module loading, readiness, and shutdown phases, including custom hook registration and emission. ```typescript import { LifecycleHookUnit, LifecycleHook } from '@artus/core'; import { Application } from '@artus/core'; @LifecycleHookUnit() export class AppLifecycle { @LifecycleHook('configWillLoad') async onConfigWillLoad() { console.log('Config about to load - last chance to modify'); } @LifecycleHook('configDidLoad') async onConfigDidLoad({ app }: { app: Application }) { console.log('Config loaded:', app.config); } @LifecycleHook('didLoad') async onDidLoad() { console.log('All modules loaded'); } @LifecycleHook('willReady') async onWillReady({ app }: { app: Application }) { console.log('Application will be ready - start servers here'); // Start HTTP server, connect to databases, etc. } @LifecycleHook('didReady') async onDidReady() { console.log('Application is ready'); } @LifecycleHook('beforeClose') async onBeforeClose() { console.log('Application shutting down - cleanup resources'); } } // Register custom hook programmatically app.registerHook('customHook', async ({ app, lifecycleManager }) => { console.log('Custom hook executed'); }); // Emit custom hook await app.lifecycleManager.emitHook('customHook'); ``` -------------------------------- ### Plugin System with Dependency Resolution (TypeScript) Source: https://context7.com/artusjs/core/llms.txt Illustrates how to define and manage plugins within an Artus.js application, including specifying dependencies between plugins. The system automatically resolves and sorts plugins based on their declared dependencies. ```typescript import path from 'path'; import { PluginFactory, PluginConfig } from '@artus/core'; // Plugin configuration const pluginConfig: PluginConfig = { 'plugin-a': { enable: true, path: path.resolve(__dirname, './plugins/plugin_a'), metadata: { name: 'plugin-a', dependencies: [{ name: 'plugin-b' }] // Requires plugin-b } }, 'plugin-b': { enable: true, path: path.resolve(__dirname, './plugins/plugin_b'), metadata: { name: 'plugin-b', dependencies: [{ name: 'plugin-c' }] } }, 'plugin-c': { enable: true, path: path.resolve(__dirname, './plugins/plugin_c'), metadata: { name: 'plugin-c' } }, 'plugin-d': { enable: true, path: path.resolve(__dirname, './plugins/plugin_d'), metadata: { name: 'plugin-d', dependencies: [ { name: 'plugin-c', optional: true } // Optional dependency ] } } }; // Plugins are automatically sorted by dependencies const pluginList = await PluginFactory.createFromConfig(pluginConfig, { logger: app.logger }); console.log(pluginList.map(p => p.name)); // Output: ['plugin-c', 'plugin-b', 'plugin-a', 'plugin-d'] // Plugin metadata in meta.json // { // "name": "plugin-a", // "dependencies": [ // { "name": "plugin-b" }, // { "name": "plugin-optional", "optional": true } // ], // "type": "module", // "configDir": "config" // } ``` -------------------------------- ### Create Custom Loaders for Specialized Modules (TypeScript) Source: https://context7.com/artusjs/core/llms.txt Enables the creation of custom loaders to handle specialized module types beyond the default ones. This involves defining a class that extends `BaseLoader` and decorating it with `@DefineLoader`. The `load`, `is`, and `onFind` methods must be implemented to define the loading logic, file identification, and metadata collection respectively. Dependencies include '@artus/core' and '@artus/injection'. ```typescript import { BaseLoader, LoaderFactory, DefineLoader, ManifestItem } from '@artus/core'; import { Container } from '@artus/injection'; @DefineLoader('custom-loader') export class CustomLoader extends BaseLoader { async load(item: ManifestItem): Promise { // Custom loading logic const module = await import(item.path + item.extname); // Register with container if (module.default) { this.container.set({ type: module.default }); } // Access loader state from scanning phase if (item.loaderState) { console.log('Loader state:', item.loaderState); } } // Called during scanning to identify files static async is(opts: LoaderFindOptions): Promise { return opts.filename.startsWith('custom_'); } // Called during scanning to collect metadata static async onFind(opts: LoaderFindOptions): Promise { return { customMetadata: true }; } } // Register custom loader LoaderFactory.register(CustomLoader); // Add loader listeners for lifecycle events app.loaderFactory.addLoaderListener('custom-loader', { before: async () => console.log('Before loading custom modules'), after: async () => console.log('After loading custom modules') }); ``` -------------------------------- ### Manage Custom Lifecycle Hooks and Flow (TypeScript) Source: https://context7.com/artusjs/core/llms.txt Provides functionalities to manage custom lifecycle hooks and control the application's lifecycle flow. It allows inserting, appending, and registering hooks using `lifecycleManager`. Hooks can be emitted with or without payloads, and in reverse order. Lifecycle hooks can also be temporarily disabled, and custom hook units can be registered. Dependencies include '@artus/core'. ```typescript import { LifecycleManager, ArtusInjectEnum } from '@artus/core'; const lifecycleManager = app.container.get(LifecycleManager); // Insert custom hook before existing hook lifecycleManager.insertHook('didLoad', 'customBeforeLoad'); // Append hook to end lifecycleManager.appendHook('customShutdown'); // Register hook function lifecycleManager.registerHook('customBeforeLoad', async ({ app, lifecycleManager, payload }) => { console.log('Custom hook before didLoad'); // Access app instance and lifecycle manager console.log('Config:', app.config); }); // Emit hook with payload await lifecycleManager.emitHook('customBeforeLoad', { userId: 123 }); // Emit hook in reverse order (useful for cleanup) await lifecycleManager.emitHook('beforeClose', null, true); // Disable lifecycle hooks temporarily lifecycleManager.enable = false; await lifecycleManager.emitHook('someHook'); // Will not execute lifecycleManager.enable = true; // Register hook unit class @LifecycleHookUnit() class MyHooks { @LifecycleHook('customHook') async handleCustom() { console.log('Custom hook handled'); } } lifecycleManager.registerHookUnit(MyHooks); ``` -------------------------------- ### Custom Exception Filters (TypeScript) Source: https://context7.com/artusjs/core/llms.txt Details how to create custom exception filters in Artus.js to handle specific error types gracefully. This includes decorators like `@ExceptionFilter` to associate filters with particular error codes or base error classes. ```typescript import { ExceptionFilter, Injectable, ArtusStdError } from '@artus/core'; @ExceptionFilter('INVALID_USER') // Handles specific error code @Injectable() export class UserExceptionFilter { async catch(err: ArtusStdError) { console.error('User exception caught:', err.code, err.desc); // Send to logging service, return user-friendly message, etc. return { status: 400, error: err.desc, code: err.code }; } } @ExceptionFilter(Error) // Handles all Error instances @Injectable() export class GlobalExceptionFilter { async catch(err: Error) { console.error('Global exception:', err.message); return { status: 500, error: 'Internal server error' }; } } // Exception filters are automatically discovered and registered when // modules are loaded with the 'exception-filter' loader ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.