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
# npm
npm install nest-shared
# yarn
yarn add nest-shared
# 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';
// Configuration
const port = configService.getPort();
// Cryptography
const apiKey = generateAPIKey({ str: 'my-app', prefix: 'app', size: 32 });
const encoded = encode({ text: 'hello world' });CommonJS
const { configService, generateAPIKey, encode } = require('nest-shared');
const port = configService.getPort();
const apiKey = generateAPIKey({ str: 'my-app', prefix: 'app', size: 32 });
const encoded = encode({ text: 'hello world' });๐ Usage Examples
Configuration Management
import { configService } from 'nest-shared';
const port = configService.getPort(); // Default: 4000
const nodeEnv = configService.getNodeEnv(); // 'development' | 'production' | 'test'
const customValue = configService.get('CUSTOM_KEY', 'default-value');Framework Integration
// Express.js
import express from 'express';
import { configService } from 'nest-shared';
const app = express();
const port = configService.getPort();
app.listen(port, () => console.log(`๐ Server running on port ${port}`));
// Fastify
import Fastify from 'fastify';
const fastify = Fastify({ logger: true });
await fastify.listen({ port: configService.getPort() });Constants
import { NODE_PORT, CACHE_TTL, VALID_UUID_REGEX } from 'nest-shared';
console.log('Port:', NODE_PORT); // 4000
console.log('Cache TTL:', CACHE_TTL); // 3600
console.log('UUID Valid:', VALID_UUID_REGEX.test('28aebbd6-173b-4375-99eb-56dc04ec2bcb'));Cryptographic Utilities
import { generateAPIKey, encode, decode, randomUUID, validateUUID } from 'nest-shared';
// API Key Generation
const apiKey = generateAPIKey({ str: 'my-app', prefix: 'app', size: 32 });
// app_3f4a9b2c1d5e6f7g8h9i0j1k2l3m4n5o
// Base64 Encoding
const encoded = encode({ text: 'Hello World!' }); // SGVsbG8gV29ybGQh
const decoded = decode({ text: encoded }); // Hello World!
// UUID Utilities
const uuid = randomUUID(); // f47ac10b-58cc-4372-a567-0e02b2c3d479
const isValid = validateUUID(uuid); // trueHelper Functions
import { RandomNumber, sum, formatDate, addDays, axiosErrorHandler } from 'nest-shared';
// Math
const random = RandomNumber(1, 100);
const total = sum([1, 2, 3, 4, 5]); // 15
// Time
const today = new Date();
const formatted = formatDate(today, 'YYYY-MM-DD');
const futureDate = addDays(today, 7);
// HTTP
const response = await axios.get('/api/data').catch(axiosErrorHandler);Buffer Base Implementation
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');
}
}๐ 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') |
File Service (FileService)
Initialize with { AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY }.
| Method | Description | Parameters | Return Type |
|---|---|---|---|
filesInterceptor(args) |
Create NestJS FilesInterceptor for S3 | FilesInterceptorInterfaceArgs |
Type<NestInterceptor> |
getS3FileURL(req) |
Get uploaded file URL from request | Request |
URL | null |
getS3FileKey(req) |
Get uploaded file Key from request | Request |
string | null |
getSignedUrl(key, expires, bucket) |
Generate presigned URL | string, number, string |
Promise<URL> |
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๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
Quick Contributing Steps
- Fork the repository
- Clone your fork:
git clone https://github.com/your-username/nest-shared.git - Install dependencies:
npm install - Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and test:
npm test - Commit and push:
git commit -m "feat: add amazing feature" - Open a Pull Request
Development Commands
npm test # Run tests
npm run test:cov # Run tests with coverage
npm run lint # Run linting
npm run format # Format code
npm run build # Build project๐ Support
If you find this project helpful:
- โญ Give a Star on GitHub
- โ Buy Me a Coffee
- ๐ฆ Share with your team and community
๐ License
Copyright ยฉ 2023โ2026 hebertcisco.
This project is licensed under the MIT License.
Made with โค๏ธ for the NestJS community
โญ Star this repo โข ๐ Report bugs โข ๐ก Request features