JSPM

  • Created
  • Published
  • Downloads 107
  • Score
    100M100P100Q75335F
  • License MIT

Shared code for nestjs projects

Package Exports

  • nest-shared
  • nest-shared/lib/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (nest-shared) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Nest Shared Logo

Nest Shared

Shared helpers, contracts and configuration utilities for NestJS/TypeScript projects

๐Ÿ“– Table of Contents

โœจ Features

  • ๐Ÿ”ง Configuration Management: Centralized configuration service for your NestJS applications
  • ๐Ÿ” Cryptographic Utilities: Base64 encoding/decoding, API key generation, UUID validation
  • ๐Ÿ“ฆ Helper Functions: Time utilities, math functions, file operations, HTTP helpers
  • ๐Ÿ—๏ธ Base Contracts: Reusable interfaces and abstract classes for common patterns
  • ๐Ÿงช Testing Support: Built-in testing utilities and mocks
  • ๐Ÿ“‹ Constants: Predefined constants for common use cases
  • ๐Ÿš€ Framework Agnostic: Works with Express, Fastify, and other Node.js frameworks
  • ๐Ÿ“ฆ TypeScript First: Full TypeScript support with comprehensive type definitions
  • ๐Ÿ” Well Tested: Comprehensive test coverage with Jest

๐Ÿ“ฆ Installation

Using npm

npm install nest-shared

Using yarn

yarn add nest-shared

Using pnpm

pnpm add nest-shared

๐Ÿ“‹ Requirements

  • Node.js: >= 20.18.1
  • TypeScript: >= 5.9
  • npm: >= 10.8.2

๐Ÿš€ Quick Start

import { configService, generateAPIKey, encode } from 'nest-shared';

// Use configuration service
const port = configService.getPort();

// Generate API key
const apiKey = generateAPIKey({
  str: 'my-app',
  prefix: 'app',
  size: 32
});

// Base64 encoding
const encoded = encode({ text: 'hello world' });

CommonJS

const { configService, generateAPIKey, encode } = require('nest-shared');

// Same functionality as above
const port = configService.getPort();
const apiKey = generateAPIKey({ str: 'my-app', prefix: 'app', size: 32 });
const encoded = encode({ text: 'hello world' });

Import the lib with ES Modules or CommonJS:

// es6
import shared from 'nest-shared';
// cjs
const shared = require('nest-shared');

๐Ÿ“– Usage Examples

Configuration Management

The configService provides centralized configuration management for your application:

import { configService } from 'nest-shared';

// Get application port
const port = configService.getPort(); // Default: 4000

// Get Node environment
const nodeEnv = configService.getNodeEnv(); // 'development' | 'production' | 'test'

// Get custom configuration values
const customValue = configService.get('CUSTOM_KEY', 'default-value');

Express.js Integration

import express from 'express';
import { configService } from 'nest-shared';

const app = express();
const port = configService.getPort();

app.get('/', (req, res) => {
  res.json({ message: 'Server is running!', port });
});

app.listen(port, () => {
  console.log(`๐Ÿš€ Server running on port ${port}`);
});

Fastify Integration

import Fastify from 'fastify';
import { configService } from 'nest-shared';

const fastify = Fastify({ logger: true });
const port = configService.getPort();

fastify.get('/', async (request, reply) => {
  return { message: 'Fastify server is running!', port };
});

const start = async () => {
  try {
    await fastify.listen({ port });
    console.log(`โšก Fastify server running on port ${port}`);
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();

Constants

Pre-defined constants for common use cases:

import {
  NODE_PORT,
  CACHE_TTL,
  CACHE_TTL_50_SEC,
  API_HEADER_OPTIONS,
  WEBSOCKET_PORT,
  VALID_UUID_REGEX,
} from 'nest-shared';

console.log('Application Port:', NODE_PORT); // 4000
console.log('Cache TTL (1 hour):', CACHE_TTL); // 3600
console.log('Cache TTL (50 seconds):', CACHE_TTL_50_SEC); // 50
console.log('API Header Options:', API_HEADER_OPTIONS); // []
console.log('WebSocket Port:', WEBSOCKET_PORT); // 4001
console.log('UUID Validation:', VALID_UUID_REGEX.test('28aebbd6-173b-4375-99eb-56dc04ec2bcb')); // true

Cryptographic Utilities

API Key Generation

import { generateAPIKey } from 'nest-shared';

// Basic API key generation
const apiKey = generateAPIKey({
  str: 'my-application',
  prefix: 'app',
  size: 32,
});
console.log(apiKey); // app_3f4a9b2c1d5e6f7g8h9i0j1k2l3m4n5o

// Advanced API key with custom digest
const secureKey = generateAPIKey({
  str: 'secure-data',
  prefix: 'sec',
  digest: 'hex',
  size: 64,
});
console.log(secureKey); // sec_a7b8c9d0e1f2g3h4i5j6k7l8m9n0o1p2q3r4s5t6u7v8w9x0y1z2

Base64 Encoding/Decoding

import { encode, decode } from 'nest-shared';

// Encode text to Base64
const encoded = encode({ text: 'Hello World!' });
console.log(encoded); // SGVsbG8gV29ybGQh

// Decode Base64 back to text
const decoded = decode({ text: encoded });
console.log(decoded); // Hello World!

// Encode JSON data
const jsonData = { user: 'john', role: 'admin' };
const encodedJson = encode({ text: JSON.stringify(jsonData) });
console.log(encodedJson); // eyJ1c2VyIjoiam9obiIsInJvbGUiOiJhZG1pbiJ9

UUID Utilities

import { validateUUID, randomUUID } from 'nest-shared';

// Generate random UUID
const newUUID = randomUUID();
console.log(newUUID); // f47ac10b-58cc-4372-a567-0e02b2c3d479

// Validate UUID format
const isValid = validateUUID('f47ac10b-58cc-4372-a567-0e02b2c3d479');
console.log(isValid); // true

const isInvalid = validateUUID('not-a-uuid');
console.log(isInvalid); // false

Buffer Base Implementation

Create custom buffer implementations using the BufferBase contract:

import { BufferBase } from 'nest-shared';
import { Buffer } from 'buffer';

class CustomBuffer implements BufferBase {
  encode(data: string | Buffer): string {
    return Buffer.from(data).toString('base64');
  }
  
  decode(str: string): string {
    return Buffer.from(str, 'base64').toString('utf-8');
  }
}

const customBuffer = new CustomBuffer();

const originalText = 'Secret Message!';
const encodedText = customBuffer.encode(originalText);
const decodedText = customBuffer.decode(encodedText);

console.log('Original:', originalText); // Secret Message!
console.log('Encoded:', encodedText);   // U2VjcmV0IE1lc3NhZ2Uh
console.log('Decoded:', decodedText);   // Secret Message!

Helper Functions

Time Utilities

import { formatDate, addDays } from 'nest-shared';

const today = new Date();
const formatted = formatDate(today, 'YYYY-MM-DD');
console.log(formatted); // 2024-01-15

const futureDate = addDays(today, 7);
console.log(futureDate); // Date object 7 days from now

Math Utilities

import { RandomNumber, sum } from 'nest-shared';

// Generate random number between 1 and 100
const random = RandomNumber(1, 100);
console.log(random); // e.g., 42

// Sum array of numbers
const total = sum([1, 2, 3, 4, 5]);
console.log(total); // 15

HTTP Utilities

import { axiosErrorHandler, parseQueryParams } from 'nest-shared';

// Handle Axios errors
const response = await axios.get('/api/data').catch(axiosErrorHandler);

// Parse query parameters
const queryString = 'page=1&limit=10&sort=name';
const params = parseQueryParams(queryString);
console.log(params); // { page: '1', limit: '10', sort: 'name' }

๐Ÿ“š API Documentation

Configuration Service (configService)

Method Description Return Type Example
getPort() Get application port number number configService.getPort() // 4000
getNodeEnv() Get Node.js environment NodeEnvType configService.getNodeEnv() // 'development'
get(key, defaultValue?) Get configuration value by key T | undefined configService.get('DB_HOST', 'localhost')

Cryptographic Utilities

Function Description Parameters Return Type
generateAPIKey(options) Generate secure API key { str, prefix?, digest?, size? } string
encode(options) Base64 encode text { text } string
decode(options) Base64 decode text { text } string
validateUUID(uuid) Validate UUID format string boolean
randomUUID() Generate random UUID - string

Helper Functions

Function Description Parameters Return Type
RandomNumber(min, max) Generate random number number, number number
sum(numbers) Sum array of numbers number[] number
formatDate(date, format) Format date Date, string string
addDays(date, days) Add days to date Date, number Date
parseQueryParams(query) Parse query string string Record<string, string>
axiosErrorHandler(error) Handle Axios errors any void

Constants

Constant Value Description
NODE_PORT 4000 Default application port
CACHE_TTL 3600 Cache TTL in seconds (1 hour)
CACHE_TTL_50_SEC 50 Cache TTL in seconds (50 seconds)
WEBSOCKET_PORT 4001 Default WebSocket port
API_HEADER_OPTIONS [] Default API header options
VALID_UUID_REGEX RegExp UUID validation regex

๐Ÿ“ File Structure

nest-shared/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ config/                    # Configuration management
โ”‚   โ”‚   โ”œโ”€โ”€ application.config.ts  # Main configuration service
โ”‚   โ”‚   โ””โ”€โ”€ index.ts              # Config exports
โ”‚   โ”œโ”€โ”€ modules/                   # Feature modules
โ”‚   โ”‚   โ””โ”€โ”€ file/                 # File handling module
โ”‚   โ”‚       โ”œโ”€โ”€ interfaces/       # File interfaces
โ”‚   โ”‚       โ”œโ”€โ”€ services/         # File services
โ”‚   โ”‚       โ””โ”€โ”€ types/            # File types
โ”‚   โ””โ”€โ”€ shared/                    # Shared utilities
โ”‚       โ”œโ”€โ”€ constants/            # Application constants
โ”‚       โ”œโ”€โ”€ contract/             # Base contracts and interfaces
โ”‚       โ”‚   โ”œโ”€โ”€ base/             # Base classes
โ”‚       โ”‚   โ”œโ”€โ”€ entity/           # Common entities
โ”‚       โ”‚   โ”œโ”€โ”€ interfaces/       # Shared interfaces
โ”‚       โ”‚   โ””โ”€โ”€ types/            # TypeScript types
โ”‚       โ”œโ”€โ”€ helpers/              # Utility functions
โ”‚       โ”‚   โ”œโ”€โ”€ class/            # Class utilities
โ”‚       โ”‚   โ”œโ”€โ”€ crypto/           # Cryptographic utilities
โ”‚       โ”‚   โ”œโ”€โ”€ fs/               # File system utilities
โ”‚       โ”‚   โ”œโ”€โ”€ http/             # HTTP utilities
โ”‚       โ”‚   โ”œโ”€โ”€ math/             # Math utilities
โ”‚       โ”‚   โ””โ”€โ”€ time/             # Time utilities
โ”‚       โ””โ”€โ”€ testing/              # Testing utilities
โ”œโ”€โ”€ examples/                      # Usage examples
โ”œโ”€โ”€ lib/                          # Compiled JavaScript
โ””โ”€โ”€ docs/                         # Documentation

File structure

โ”œโ”€โ”€ src
โ”‚   โ”œโ”€โ”€ config
โ”‚   โ”‚   โ””โ”€โ”€ application.config.ts
โ”‚   โ”œโ”€โ”€ modules
โ”‚   โ”‚   โ””โ”€โ”€ file
โ”‚   โ”‚       โ”œโ”€โ”€ interfaces
โ”‚   โ”‚       โ”œโ”€โ”€ services
โ”‚   โ”‚       โ””โ”€โ”€ types
โ”‚   โ””โ”€โ”€ shared
โ”‚       โ”œโ”€โ”€ constants
โ”‚       โ”œโ”€โ”€ contract
โ”‚       โ”‚   โ”œโ”€โ”€ base
โ”‚       โ”‚   โ”œโ”€โ”€ entity
โ”‚       โ”‚   โ”œโ”€โ”€ interfaces
โ”‚       โ”‚   โ””โ”€โ”€ types
โ”‚       โ””โ”€โ”€ helpers
โ”‚           โ”œโ”€โ”€ class
โ”‚           โ”œโ”€โ”€ crypto
โ”‚           โ”œโ”€โ”€ fs
โ”‚           โ”œโ”€โ”€ http
โ”‚           โ”œโ”€โ”€ math
โ”‚           โ””โ”€โ”€ time

๐Ÿค Contributing

We welcome contributions from the community! Here's how you can help:

๐Ÿš€ Getting Started

  1. Fork the repository on GitHub
  2. Clone your fork locally:
    git clone https://github.com/your-username/nest-shared.git
    cd nest-shared
  3. Install dependencies:
    npm install
  4. Create a feature branch:
    git checkout -b feature/amazing-feature

๐Ÿ› ๏ธ Development Workflow

  1. Make your changes to the codebase
  2. Run tests to ensure everything works:
    npm test
  3. Run linting to check code quality:
    npm run lint
  4. Format your code:
    npm run format
  5. Build the project:
    npm run build

๐Ÿ“‹ Submitting Changes

  1. Commit your changes with a clear message:
    git commit -m "feat: add amazing new feature"
  2. Push to your fork:
    git push origin feature/amazing-feature
  3. Open a Pull Request on GitHub

๐ŸŽฏ What We're Looking For

  • Bug fixes and performance improvements
  • New features that align with the project's goals
  • Documentation improvements
  • Test coverage improvements
  • Examples and use cases

๐Ÿ“ Code Standards

  • Follow the existing code style and conventions
  • Write meaningful commit messages following Conventional Commits
  • Add tests for new features
  • Update documentation as needed
  • Ensure TypeScript types are properly defined

๐Ÿ› Reporting Issues

Found a bug or have a feature request? Please check our issues page first to avoid duplicates. When reporting issues, please include:

  • Clear description of the problem
  • Steps to reproduce the issue
  • Expected behavior vs actual behavior
  • Environment details (Node.js version, OS, etc.)
  • Code samples if applicable

๐Ÿ’– Support

If you find this project helpful, please consider supporting it:

โญ Give a Star

Show your support by giving this repository a โญ on GitHub!

โ˜• Buy Me a Coffee

Help fuel development by buying me a coffee:

Buy Me A Coffee

๐ŸŒŸ Spread the Word

Share this project with others who might find it useful!

  • โญ Star the repository
  • ๐Ÿฆ Tweet about it
  • ๐Ÿ“ง Share with your team
  • ๐Ÿ“ Blog about your experience

๐Ÿ“„ License

Copyright ยฉ 2023โ€“2026 hebertcisco.

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ“‹ License Summary

You are free to:

  • โœ… Use the software for any purpose
  • โœ… Modify the software
  • โœ… Distribute the software
  • โœ… Use the software commercially

Under the following conditions:

  • ๐Ÿ“„ License and copyright notice must be included

๐Ÿ™ Acknowledgments

  • Thanks to all contributors who have helped make this project better
  • Special thanks to the NestJS team for creating such an amazing framework
  • Gratitude to the TypeScript team for providing excellent type safety

Made with โค๏ธ for the NestJS community

โญ Star this repo โ€ข ๐Ÿ› Report bugs โ€ข ๐Ÿ’ก Request features