contactship-core-server
v1.0.2
Published
Core SDK for Contactship Server
Maintainers
Readme
Contactship Core Server
Core SDK for Contactship Server providing essential utilities for HTTP services, logging, error handling, validation, and middleware management.
Features
- 🚀 HTTP Service: Powerful HTTP client based on Axios with interceptor support
- 📝 Logging: Structured logging with Pino and custom log levels
- ❌ Error Handling: Comprehensive error handling with custom error classes
- ✅ Validation: Request validation with Joi integration
- 🔧 Middlewares: Useful Express middlewares (catchAsync, catchRedirect, validate)
- 🛠️ Utilities: Format, time, and validation utilities
Installation
npm install contactship-core-serverQuick Start
HTTP Service
import { HttpService, TypeInterceptor } from 'contactship-core-server';
const httpService = new HttpService('https://api.example.com');
// GET request
const response = await httpService.get('/users');
// POST request
const newUser = await httpService.post('/users', {
data: { name: 'John', email: '[email protected]' }
});
// Configure interceptors
httpService.configureInterceptors(
TypeInterceptor.REQUEST,
(config) => {
config.headers.Authorization = `Bearer ${token}`;
return config;
}
);Logger
import { Logger, TypeLogger } from 'contactship-core-server';
Logger.info('Application started');
Logger.error('An error occurred');
Logger.http('HTTP request received');
Logger.debug('Debug information');
Logger.warn('Warning message');Error Handling
import { CustomError, errorHandler, handlerHttpError, CodeError } from 'contactship-core-server';
// Throw custom error
throw new CustomError('User not found', {
code: CodeError.UNKNOWN_ERROR,
statusCode: 404,
metadata: { userId: 123 }
});
// Use error handler middleware in Express
app.use(errorHandler);
// Handle errors manually in route handlers
try {
// Your code
} catch (error) {
handlerHttpError(error, res, { showMessage: true });
}Request Validation
import { validateMiddleware } from 'contactship-core-server';
import Joi from 'joi';
const userSchema = {
body: Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
age: Joi.number().min(18)
})
};
app.post('/users', validateMiddleware(userSchema), (req, res) => {
// Request body is validated and type-safe
const { name, email, age } = req.body;
res.json({ success: true });
});Async Error Handling Middleware
import { catchAsync, CustomError, CodeError } from 'contactship-core-server';
app.get('/users/:id', catchAsync(async (req, res) => {
const user = await getUserById(req.params.id);
if (!user) {
throw new CustomError('User not found', {
code: CodeError.UNKNOWN_ERROR,
statusCode: 404
});
}
res.json(user);
}));Redirect Error Handling
import { catchRedirect } from 'contactship-core-server';
app.get('/protected', catchRedirect(
async (req, res) => {
// Your protected route logic
},
'/login', // Redirect URL on error
'error' // Query param name for error message
));HTTP Response Helpers
import { handlerHttpResponse, createSuccessResponse } from 'contactship-core-server';
// Send formatted success response
handlerHttpResponse(res, {
data: { users: [] },
statusCode: 200,
message: 'Users retrieved successfully'
});
// Create response object
const response = createSuccessResponse({ userId: 123 }, 201);Configuration
import { configure, getConfig, setConfigValue, getConfigValue, resetConfig } from 'contactship-core-server';
// Configure the SDK
configure({
env: 'production',
debug: false,
securityBypass: false,
secretKey: process.env.SECRET_KEY,
privateKey: process.env.PRIVATE_KEY
});
// Get current config
const config = getConfig();
console.log(config.env); // 'production'
// Get a specific config value
const env = getConfigValue('env');
// Set a specific config value
setConfigValue('debug', true);
// Reset to default configuration
resetConfig();Utilities
import {
formatBasePath,
hoursToMilliseconds,
sanitizeErrorMessage,
generateRandomString,
jsonStringify,
sleep,
now,
secondsToMs,
minutesToMs,
hoursToMs,
daysToMs,
pick,
isValidStatusCode,
isPositiveNumber,
isValidTimeStamp,
isCustomError,
isHttpResponse
} from 'contactship-core-server';
// Format base path
const path = formatBasePath('/api/v1'); // '/api/v1/'
// Time utilities
await sleep(1000); // Wait 1 second
const timestamp = now(); // Get current timestamp
const ms1 = secondsToMs(30); // Convert 30 seconds to ms
const ms2 = minutesToMs(5); // Convert 5 minutes to ms
const ms3 = hoursToMs(2); // Convert 2 hours to ms
const ms4 = daysToMs(1); // Convert 1 day to ms
const ms5 = hoursToMilliseconds(2); // Convert 2 hours to ms (legacy)
// JSON utilities
const jsonStr = jsonStringify({ name: 'John' }); // Stringify object
const safeJsonStr = jsonStringify(circularObj, true); // Handle circular refs
// Validation utilities
isValidStatusCode(200); // true
isPositiveNumber(5); // true
isValidTimeStamp(Date.now()); // true
isCustomError(error); // Check if CustomError instance
isHttpResponse(response); // Check if Axios response
// Generate random string
const randomId = generateRandomString(10);
// Pick specific properties from object
const picked = pick({ a: 1, b: 2, c: 3 }, ['a', 'c']); // { a: 1, c: 3 }
// Sanitize error message
const cleanMessage = sanitizeErrorMessage(error.message, 'Default error');API Reference
Classes
- HttpService: HTTP client with interceptor support
- CustomError: Enhanced error class with metadata and data support
- Logger: Structured logging with custom levels
- FlowLogger: Flow-specific logging
- HttpLogger: HTTP request/response logging
Middlewares
- catchAsync: Wraps async route handlers to catch errors
- catchRedirect: Redirects on errors with error message in query param
- validateMiddleware: Validates request data using Joi schemas
- errorHandler: Global error handler middleware
Handlers
- handlerHttpError: Handles errors and sends formatted response
- handlerHttpResponse: Sends formatted success response
- formatHttpResponse: Formats response into standard structure
- createSuccessResponse: Creates success response object
- createErrorResponse: Creates error response object
Enums
- TypeLogger: Log levels (ERROR, WARN, INFO, HTTP, HTTP_FAIL, DEBUG)
- HttpStatus: HTTP status codes
- CodeError: Application error codes
- TypeInterceptor: Interceptor types (REQUEST, RESPONSE)
TypeScript Support
This package is written in TypeScript and provides complete type definitions.
import {
IHttpResponse,
ICustomError,
IResponseCore,
CustomLogger
} from 'contactship-core-server';License
ISC
