@timmons-group/snack-utils
v0.2.1
Published
Essential utilities for building robust serverless Node.js applications. This package provides logging, profiling, and HTTP response utilities optimized for Lambda and serverless environments.
Maintainers
Keywords
Readme
Shared Node Architecture Component Kit (SNACK) Utils
Essential utilities for building robust serverless Node.js applications. This package provides logging, profiling, and HTTP response utilities optimized for Lambda and serverless environments.
Installation
npm install @timmons-group/snack-utilsComponents
Logger
A configurable logging utility with multiple log levels and structured output, designed for serverless environments.
Features
- Multiple Log Levels: ERROR, WARN, INFO
- Module-based Logging: Create loggers for specific modules
- Environment Configuration: Control logging via environment variables
- Structured Output: Consistent log message formatting
- Performance Optimized: Minimal overhead when logging is disabled
Configuration
Set the LOG_LEVEL environment variable to control logging output:
ERROR- Only error messages (default)WARN- Warning and error messagesINFO- All messages (info, warning, error)
Usage
import { createLoggers, setLogLevel } from '@timmons-group/snack-utils';
// Create module-specific loggers
const { log, warn, error } = createLoggers('UserService');
// Log messages at different levels
log('Processing user request'); // Info level
warn('User session expires soon'); // Warning level
error('Failed to authenticate user'); // Error level
// Programmatically set log level
setLogLevel('INFO');Advanced Usage:
import { createLoggers } from '@timmons-group/snack-utils';
// Multiple modules
const userLogger = createLoggers('UserService');
const dbLogger = createLoggers('DatabaseService');
userLogger.log('User authenticated successfully');
dbLogger.warn('Connection pool running low');Profiler
A lightweight performance profiling utility for measuring execution time across different code blocks.
Features
- Code Block Timing: Measure execution time between markers
- Nested Profiling: Support for hierarchical timing measurements
- Detailed Reports: Comprehensive timing analysis
- Memory Efficient: Minimal memory footprint
- Easy Integration: Simple API for existing code
Usage
import { createProfiler } from '@timmons-group/snack-utils';
const profiler = createProfiler();
// Mark timing points
profiler.tab('Database Query');
const users = await db.query('SELECT * FROM users');
profiler.tab('Data Processing');
const processedUsers = users.map(processUser);
profiler.tab('Response Formatting');
const response = formatResponse(processedUsers);
profiler.end();
// Generate timing report
profiler.report();
// Output:
// Database Query: 45ms
// Data Processing: 12ms
// Response Formatting: 3ms
// Total: 60msAdvanced Profiling:
import { createProfiler } from '@timmons-group/snack-utils';
const profiler = createProfiler();
// Measure API endpoint performance
profiler.tab('Request Validation');
validateRequest(event);
profiler.tab('Authentication');
const user = await authenticateUser(token);
profiler.tab('Business Logic');
const result = await processBusinessLogic(user, data);
profiler.tab('Response Generation');
const response = generateResponse(result);
profiler.end();
profiler.report(); // Detailed breakdown of each operationHTTP Responses
Standardized HTTP response utilities for AWS Lambda functions with consistent formatting and proper headers.
Features
- Standard Status Codes: Pre-configured common HTTP responses
- CORS Support: Automatic CORS header handling
- JSON Serialization: Automatic JSON response formatting
- Lambda Optimized: Designed for AWS Lambda return format
- Type Safety: Consistent response structure
Available Response Types
jsonSuccess(data)- 200 OK with JSON datanoContent()- 204 No ContentnotFound(message?)- 404 Not FoundbadRequest(message?)- 400 Bad Requestunauthorized(message?)- 401 Unauthorizedforbidden(message?)- 403 ForbiddenserverError(message?)- 500 Internal Server Error
Usage
import { responses } from '@timmons-group/snack-utils';
// Success response with data
const users = await getUsers();
return responses.jsonSuccess(users);
// Error responses
if (!isValidInput(data)) {
return responses.badRequest('Invalid input data');
}
if (!isAuthenticated(user)) {
return responses.unauthorized('Authentication required');
}
if (!hasPermission(user, 'read')) {
return responses.forbidden('Insufficient permissions');
}
// No content response
await deleteUser(userId);
return responses.noContent();Individual Imports:
import { jsonSuccess, badRequest, serverError } from '@timmons-group/snack-utils/responses';
// Use specific response functions
export const handler = async (event) => {
try {
const data = await processRequest(event);
return jsonSuccess(data);
} catch (error) {
if (error.code === 'VALIDATION_ERROR') {
return badRequest(error.message);
}
return serverError('An unexpected error occurred');
}
};Custom Response Headers:
import { jsonSuccess } from '@timmons-group/snack-utils/responses';
// The responses automatically include CORS headers and Content-Type
const response = jsonSuccess({ message: 'Success' });
// Returns:
// {
// statusCode: 200,
// headers: {
// 'Content-Type': 'application/json',
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Headers': 'Content-Type',
// 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
// },
// body: '{"message":"Success"}'
// }Complete Example
import { createLoggers } from '@timmons-group/snack-utils/logger';
import { createProfiler } from '@timmons-group/snack-utils/profiler';
import { responses } from '@timmons-group/snack-utils/responses';
const { log, error } = createLoggers('UserAPI');
export const handler = async (event) => {
const profiler = createProfiler();
try {
log('Processing user request');
profiler.tab('Input Validation');
const { userId } = JSON.parse(event.body);
if (!userId) {
return responses.badRequest('User ID is required');
}
profiler.tab('Database Query');
const user = await getUserById(userId);
if (!user) {
return responses.notFound('User not found');
}
profiler.tab('Response Generation');
const response = responses.jsonSuccess(user);
profiler.end();
profiler.report();
return response;
} catch (err) {
error('Request failed:', err.message);
return responses.serverError('Internal server error');
}
};Environment Variables
LOG_LEVEL- Controls logging verbosity (ERROR, WARN, INFO)
Exports
// All utilities
import { createLoggers, setLogLevel, createProfiler, responses } from '@timmons-group/snack-utils';
// Individual utilities
import { createLoggers } from '@timmons-group/snack-utils/logger';
import { createProfiler } from '@timmons-group/snack-utils/profiler';
import { responses, jsonSuccess } from '@timmons-group/snack-utils/responses';Best Practices
- Create Module Loggers: Use descriptive module names for better log organization
- Profile Critical Paths: Use profiler for performance-sensitive operations
- Consistent Responses: Use response utilities for uniform API responses
- Environment-based Logging: Set appropriate log levels for different environments
- Error Handling: Always use proper HTTP status codes for different error scenarios
Roadmap
- [x] Logger with multiple levels
- [x] Performance profiler
- [x] HTTP response utilities
- [x] CORS support
- [ ] Structured logging (JSON format)
- [ ] Log aggregation support
- [ ] Metrics collection
- [ ] Request tracing
- [ ] Response caching utilities
