@dc41/core-services
v0.0.6
Published
Independent core modules for React Native applications
Maintainers
Readme
Core Modules - Independent NPM Package
This directory contains independent core modules that can be used as a standalone npm package. Each module is designed to work without external dependencies and provides fallback implementations when optional dependencies are not available.
Architecture
Dependency Injection Pattern
Each module follows a dependency injection pattern with abstract interfaces and multiple implementations:
- Abstract Interfaces (
dependencies.ts) - Define contracts - Default Implementations - In-memory/fallback implementations
- Optional Implementations - Native/optimized implementations when dependencies are available
Module Structure
src/core/
├── dependencies.ts # Abstract interfaces and default implementations
├── logger.ts # Independent logging with fallback
├── types.ts # Core type definitions
├── AppConfig/ # Application configuration
├── EventEmitter/ # Event system
├── ReactQuery/ # Query client with fallback
├── services/ # Service layer
│ ├── api/ # HTTP services with fetch fallback
│ └── storage/ # Storage with AsyncStorage fallback
└── UI/ # UI componentsModules
1. Logger (logger.ts)
Independent logging system with configurable output.
Features:
- Timestamp formatting
- Environment-aware logging
- Configurable prefixes
- No external dependencies
Usage:
import { createLogger, defaultLogger } from '@core';
const logger = createLogger({ enabled: true, prefix: 'MY_APP' });
logger('User logged in', { userId: 123 });
// Or use default logger
defaultLogger('App started');2. Storage (services/storage/)
Cross-platform storage with fallback implementations.
Features:
- AsyncStorage support (when available)
- In-memory fallback
- Type-safe storage keys
- Automatic JSON serialization
Usage:
import { storage } from '@core';
// Set data
await storage.set('user', { name: 'John', age: 30 });
// Get data
const user = await storage.get('user');
// Remove data
await storage.remove('user');3. Secure Storage (services/storage/SecureStorage.service.ts)
Secure storage with biometric support and fallback.
Features:
- Keychain support (when available)
- In-memory fallback
- Biometric authentication support
- Secure data handling
Usage:
import { secureStorage } from '@core';
// Set secure data
await secureStorage.set('token', 'secret-token', {
requiresBiometric: true
});
// Get secure data
const token = await secureStorage.get('token', {
requiresBiometric: true
});4. HTTP Service (services/api/BaseRequest.service.ts)
HTTP client with fetch fallback and optional Axios support.
Features:
- Fetch API support (always available)
- Axios support (when available)
- Request/response logging
- Error handling
- Timeout support
Usage:
import { httpService } from '@core';
const response = await httpService.request({
method: 'GET',
url: '/api/users',
headers: { 'Authorization': 'Bearer token' }
});5. Query Client (ReactQuery/queryClient.ts)
Lightweight query client with caching and fallback.
Features:
- In-memory caching
- Stale data handling
- Development logging
- No external dependencies
Usage:
import { queryClient } from '@core';
// Set query data
queryClient.setQueryData('users', [{ id: 1, name: 'John' }]);
// Get query data
const users = queryClient.getQueryData('users');
// Invalidate queries
queryClient.invalidateQueries('users');6. Event System (EventEmitter/)
Type-safe event system for communication between modules.
Features:
- Type-safe events
- Event registration and cleanup
- Development logging
- No external dependencies
Usage:
import { GlobalEventBus } from '@core';
// Listen to events
const unsubscribe = GlobalEventBus.on('user:login', (data) => {
console.log('User logged in:', data);
});
// Emit events
GlobalEventBus.emit('user:login', { userId: 123 });
// Cleanup
unsubscribe();Independence Guarantees
No External Dependencies Required
Each module provides:
- Default Implementation: Always works without external dependencies
- Optional Enhancement: Uses native libraries when available
- Automatic Fallback: Seamlessly switches between implementations
Environment Compatibility
- Web: Works in browser environments
- Node.js: Works in server environments
- React Native: Works with or without native modules
- Development: Enhanced logging and debugging
Type Safety
All modules maintain full TypeScript support:
- Strict type checking
- Interface contracts
- Generic type support
- Development-time safety
Usage as NPM Package
Installation
npm install @your-org/core-modules
# or
yarn add @your-org/core-modulesBasic Usage
import {
defaultLogger,
storage,
secureStorage,
httpService,
queryClient,
GlobalEventBus
} from '@your-org/core-modules';
// Configure logger
defaultLogger('App starting...');
// Use storage
await storage.set('config', { theme: 'dark' });
// Use HTTP service
const users = await httpService.request({
method: 'GET',
url: '/api/users'
});
// Use query client
queryClient.setQueryData('users', users);
// Use event system
GlobalEventBus.emit('app:ready');Advanced Configuration
import { createLogger } from '@your-org/core-modules';
// Custom logger configuration
const logger = createLogger({
enabled: process.env.NODE_ENV === 'development',
prefix: 'MY_APP'
});
// Custom storage with encryption
class EncryptedStorage {
constructor(private storage: typeof storage) {}
async set<T>(key: string, data: T): Promise<boolean> {
// Encrypt data before storing
const encrypted = encrypt(JSON.stringify(data));
return this.storage.set(key, encrypted);
}
}Development and Testing
Running Tests
npm test
npm run test:watchBuilding for Production
npm run buildDevelopment Mode
// Enhanced logging in development
if (process.env.NODE_ENV === 'development') {
// Development-specific logging
defaultLogger('Debug info', { state: 'development' });
}Migration Guide
From Existing Dependencies
Replace logger imports:
// Before import { logger } from '@utils'; // After import { defaultLogger } from '@core';Replace storage imports:
// Before import AsyncStorage from '@react-native-async-storage/async-storage'; // After import { storage } from '@core';Replace HTTP client:
// Before import axios from 'axios'; // After import { httpService } from '@core';
Benefits of Migration
- Reduced bundle size: No external dependencies required
- Better compatibility: Works across all environments
- Easier testing: Mock implementations available
- Type safety: Full TypeScript support
- Future-proof: Abstract interfaces allow easy swapping
Contributing
Adding New Modules
- Define abstract interface in
dependencies.ts - Create default implementation with fallback
- Add optional implementation for enhanced features
- Export from main index with proper typing
- Add tests for all implementations
Testing Guidelines
- Test default implementations thoroughly
- Test fallback behavior when dependencies are missing
- Test type safety with TypeScript
- Test cross-environment compatibility
License
This package is licensed under the MIT License.
Support
For issues and questions:
- Create an issue in the repository
- Check the documentation
- Review the test files for usage examples
