Best Practices
Code Organization
Section titled “Code Organization”Project Structure
Section titled “Project Structure”Organize your project for maintainability:
my-project/├── src/│ ├── config/│ ├── utils/│ └── index.js├── tests/└── package.jsonConfiguration Management
Section titled “Configuration Management”Keep configuration separate:
export default { name: process.env.APP_NAME || 'My App', debug: process.env.DEBUG === 'true', timeout: parseInt(process.env.TIMEOUT || '5000')};
// index.jsimport config from './config/app.js';import { createApp } from 'your-package-name';
const app = createApp(config);Error Handling
Section titled “Error Handling”Graceful Degradation
Section titled “Graceful Degradation”Always handle errors gracefully:
async function safeRun() { try { await app.run(); } catch (error) { console.error('Error:', error.message); // Fallback behavior await app.runSafeMode(); }}Logging
Section titled “Logging”Implement proper logging:
import { createApp } from 'your-package-name';
const app = createApp({ name: 'My App', logger: { level: 'info', format: 'json' }});Testing
Section titled “Testing”Unit Tests
Section titled “Unit Tests”Write comprehensive tests:
import { createApp } from 'your-package-name';import { describe, it, expect } from 'vitest';
describe('App', () => { it('should create app instance', () => { const app = createApp({ name: 'Test' }); expect(app.name).toBe('Test'); });});Security
Section titled “Security”Input Validation
Section titled “Input Validation”Always validate user input:
function validateConfig(config) { if (!config.name || typeof config.name !== 'string') { throw new Error('Invalid name'); } if (config.timeout && config.timeout < 0) { throw new Error('Invalid timeout'); } return config;}
const app = createApp(validateConfig(userConfig));Performance
Section titled “Performance”Resource Management
Section titled “Resource Management”Clean up resources properly:
async function runWithCleanup() { const app = createApp({ name: 'My App' });
try { await app.run(); } finally { await app.stop(); await app.cleanup(); }}Summary
Section titled “Summary”Following these best practices will help you:
- Write maintainable code
- Handle errors gracefully
- Ensure security
- Optimize performance