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

# 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

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); // true

Helper 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

  1. Fork the repository
  2. Clone your fork: git clone https://github.com/your-username/nest-shared.git
  3. Install dependencies: npm install
  4. Create a feature branch: git checkout -b feature/amazing-feature
  5. Make your changes and test: npm test
  6. Commit and push: git commit -m "feat: add amazing feature"
  7. 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