npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

contactship-core-server

v1.0.2

Published

Core SDK for Contactship Server

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-server

Quick 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