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
๐ Table of Contents
- Features
- Installation
- Requirements
- Quick Start
- Usage Examples
- API Documentation
- File Structure
- Contributing
- Support
- License
โจ 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-sharedUsing yarn
yarn add nest-sharedUsing pnpm
pnpm add nest-shared๐ Requirements
- Node.js: >= 20.18.1
- TypeScript: >= 5.9
- npm: >= 10.8.2
๐ Quick Start
ES Modules (Recommended)
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')); // trueCryptographic 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_a7b8c9d0e1f2g3h4i5j6k7l8m9n0o1p2q3r4s5t6u7v8w9x0y1z2Base64 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); // eyJ1c2VyIjoiam9obiIsInJvbGUiOiJhZG1pbiJ9UUID 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); // falseBuffer 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 nowMath 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); // 15HTTP 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/ # DocumentationFile 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
- Fork the repository on GitHub
- Clone your fork locally:
git clone https://github.com/your-username/nest-shared.git cd nest-shared
- Install dependencies:
npm install
- Create a feature branch:
git checkout -b feature/amazing-feature
๐ ๏ธ Development Workflow
- Make your changes to the codebase
- Run tests to ensure everything works:
npm test
- Run linting to check code quality:
npm run lint - Format your code:
npm run format
- Build the project:
npm run build
๐ Submitting Changes
- Commit your changes with a clear message:
git commit -m "feat: add amazing new feature"
- Push to your fork:
git push origin feature/amazing-feature - 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:
๐ 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