moneymaker-sdk
v0.2.2
Published
TypeScript SDK for MoneyMaker Backend API
Maintainers
Readme
@guillermo/moneymaker-sdk
TypeScript SDK for MoneyMaker Backend API - A powerful, type-safe SDK for interacting with the MoneyMaker multi-tenant backend.
🚀 Features
- ✅ Full TypeScript Support - Complete type safety and IntelliSense
- 🔐 Automatic Authentication - Auto token refresh and session management
- 🏢 Multi-tenant Ready - Built-in support for multi-tenancy
- 📦 Modular Architecture - Use only what you need
- 🔄 Retry Logic - Automatic retry on network failures
- 📊 Event System - Listen to SDK events (login, logout, errors)
- 🎯 Zero Configuration - Sensible defaults, easy to customize
- 🌐 Universal - Works in browser and Node.js
📦 Installation
npm install @guillermo/moneymaker-sdk
# or
yarn add @guillermo/moneymaker-sdk
# or
pnpm add @guillermo/moneymaker-sdk🔧 Quick Start
import { MoneyMakerSDK } from '@guillermo/moneymaker-sdk';
// Initialize the SDK
const sdk = new MoneyMakerSDK({
baseURL: 'http://localhost:3000',
clientId: 'your-client-id', // Optional
debug: true, // Enable debug logs
});
// Login
const { user, tokens } = await sdk.auth.login({
email: '[email protected]',
password: 'password123',
});
console.log('Logged in as:', user.name);
// Use the API
const products = await sdk.products.list({
page: 1,
limit: 10,
});
console.log('Products:', products.data);📖 Documentation
Initialization
const sdk = new MoneyMakerSDK({
baseURL: 'http://localhost:3000',
clientId: 'optional-client-id',
enableAutoRefresh: true, // Auto-refresh tokens (default: true)
tokenStorage: 'localStorage', // 'localStorage' | 'sessionStorage' | 'memory'
timeout: 30000, // Request timeout in ms
maxRetries: 3, // Max retry attempts
retryDelay: 1000, // Delay between retries
debug: false, // Enable debug logs
onError: (error) => console.error(error),
onTokenRefresh: (tokens) => console.log('Token refreshed'),
onLogout: () => console.log('User logged out'),
});Authentication
// Register
const { user, tokens } = await sdk.auth.register({
name: 'John Doe',
email: '[email protected]',
password: 'secure-password',
phone: '+1234567890', // Optional
});
// Login
const { user, tokens } = await sdk.auth.login({
email: '[email protected]',
password: 'secure-password',
});
// Get current user profile
const profile = await sdk.auth.getProfile();
// Check if authenticated
if (sdk.isAuthenticated()) {
console.log('User is logged in');
}
// Logout
await sdk.auth.logout();
// Forgot password
await sdk.auth.forgotPassword({
email: '[email protected]',
});
// Reset password
await sdk.auth.resetPassword({
token: 'reset-token',
password: 'new-password',
});
// Verify email
await sdk.auth.verifyEmail({
token: 'verification-token',
});Products
// List products
const products = await sdk.products.list({
page: 1,
limit: 10,
search: 'laptop',
category: 'electronics',
isActive: true,
minPrice: 100,
maxPrice: 2000,
});
// Get product by ID
const product = await sdk.products.get('product-id');
// Create product
const newProduct = await sdk.products.create({
name: 'MacBook Pro',
description: '16-inch, M3 Max',
price: 2999.99,
stock: 10,
category: 'electronics',
});
// Update product
const updated = await sdk.products.update('product-id', {
price: 2799.99,
stock: 8,
});
// Delete product
await sdk.products.delete('product-id');
// Get product statistics
const stats = await sdk.products.getStats();
console.log('Total products:', stats.totalProducts);
// Get top selling products
const topSelling = await sdk.products.getTopSelling(5);
// Get low stock products
const lowStock = await sdk.products.getLowStock(10);Users
// List users
const users = await sdk.users.list({
page: 1,
limit: 20,
});
// Get user by ID
const user = await sdk.users.get('user-id');
// Create user
const newUser = await sdk.users.create({
name: 'Jane Doe',
email: '[email protected]',
password: 'secure-password',
role: 'EMPLOYEE',
});
// Update user
await sdk.users.update('user-id', {
name: 'Jane Smith',
status: 'ACTIVE',
});
// Delete user
await sdk.users.delete('user-id');Clients (Tenants)
// List clients
const clients = await sdk.clients.list({
page: 1,
limit: 10,
search: 'company',
});
// Get client by ID
const client = await sdk.clients.get('client-id');
// Create client
const newClient = await sdk.clients.create({
name: 'Acme Corp',
email: '[email protected]',
activeServices: ['products', 'orders'],
});
// Update client
await sdk.clients.update('client-id', {
plan: 'premium',
});
// Get client count
const count = await sdk.clients.getCount();
// Get dashboard data
const dashboardData = await sdk.clients.getDashboardData('client-id');Services
// List services
const services = await sdk.services.list({
page: 1,
limit: 10,
isActive: true,
});
// Create service
const service = await sdk.services.create({
name: 'Consulting',
description: 'Business consulting service',
price: 150.00,
duration: 60, // minutes
});
// Toggle service active status
await sdk.services.toggleActive('service-id');Events
// Listen to auth events
sdk.on('auth:login', () => {
console.log('User logged in');
});
sdk.on('auth:logout', () => {
console.log('User logged out');
});
sdk.on('auth:token-refresh', (tokens) => {
console.log('Token refreshed:', tokens);
});
// Listen to errors
sdk.on('error', (error) => {
console.error('SDK Error:', error);
});Error Handling
import {
AuthenticationError,
ValidationError,
NotFoundError,
NetworkError
} from '@guillermo/moneymaker-sdk';
try {
await sdk.auth.login({ email: '[email protected]', password: 'wrong' });
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid credentials');
} else if (error instanceof ValidationError) {
console.error('Invalid input:', error.details);
} else if (error instanceof NetworkError) {
console.error('Network error, please check your connection');
}
}Advanced Usage
// Change client ID dynamically
sdk.setClientId('another-client-id');
// Enable/disable debug logs
sdk.setDebug(true);
// Get current configuration
const config = sdk.getConfig();
// Clear all stored data
sdk.clearStorage();
// Check authentication status
const isAuth = sdk.isAuthenticated();
// Get tokens directly
const accessToken = sdk.auth.getAccessToken();
const refreshToken = sdk.auth.getRefreshToken();🔐 Security
- Tokens are automatically stored in
localStorage,sessionStorage, or memory - Automatic token refresh before expiration
- Secure password handling (never stored locally)
- Support for HTTPS and custom headers
🧪 Development
# Install dependencies
npm install
# Build the SDK
npm run build
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Type checking
npm run type-check
# Lint code
npm run lint
# Format code
npm run format📝 License
MIT
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📞 Support
For support, please open an issue on GitHub or contact the development team.
