zync-nest-library
Version: 
NestJS library with database backup and file upload utilities
673 lines (529 loc) • 16.4 kB
Markdown
# Zync NestJS Library
A comprehensive NestJS library providing database backup utilities, file upload services, and common utilities for modern web applications.
## 📦 Features
- **Database Backup Service**: Automated MongoDB backup with cloud storage support
- **File Upload Service**: Handle file uploads with image resizing and cloud storage
- **Bucket Service**: AWS S3/DigitalOcean Spaces integration
- **Firebase Service**: Push notification service with FCM integration
- **Mailer Service**: Email sending service with template support
- **Exabytes SMS Service**: SMS sending service via Exabytes API
- **UltraMsg Service**: WhatsApp messaging service via UltraMsg API
- **Message Service**: Unified messaging service for various channels
- **Utility Functions**: Common helpers for date formatting, file handling, and more
## 🚀 Installation
### Local Development
```bash
# Clone the repository
git clone <repository-url>
cd zync-nest-library
# Install dependencies
pnpm install
# Build the library
pnpm run build
```
### Using in Other Projects
#### Method 1: File Path Dependency (Recommended for pnpm)
In your project's `package.json`:
```json
{
  "dependencies": {
    "zync-nest-library": "file:../../zync-library/zync-nest-library"
  }
}
```
Then run:
```bash
pnpm install
```
#### Method 2: npm link (For npm users)
```bash
# In the library directory
npm link
# In your consuming project
npm link zync-nest-library
```
#### Method 3: pnpm link (Alternative for pnpm)
```bash
# Setup pnpm global bin directory (one-time setup)
pnpm setup
# In the library directory
pnpm link --global
# In your consuming project
pnpm link --global zync-nest-library
```
## 📚 Usage
### Basic Setup
Import the required modules in your NestJS application:
```typescript
import { Module } from '@nestjs/common';
import { 
  ApDbBackupModule, 
  UploadModule,
  FirebaseModule,
  MailerModule,
  MessageModule
} from 'zync-nest-library';
@Module({
  imports: [
    ApDbBackupModule,
    UploadModule,
    FirebaseModule,
    MailerModule,
    MessageModule,
    // ... other modules
  ],
})
export class AppModule {}
```
### Database Backup Service
The `DbBackupService` provides automated MongoDB backup functionality with optional cloud storage.
#### Configuration
```typescript
import { IDbBackupConfig } from 'zync-nest-library';
const backupConfig: IDbBackupConfig = {
  env: 'production',
  mongodb: {
    connectionStrings: 'mongodb://localhost:27017/mydb'
    // or multiple connections: ['mongodb://...', 'mongodb://...']
  },
  backup: {
    dir: './backups',
    enabled: true,
    maxBackups: 10,
    isDownload: false,
    uploadToSpace: true
  },
  spaces: {
    name: 'my-bucket',
    region: 'nyc3',
    key: 'your-access-key',
    secret: 'your-secret-key',
    endpoint: 'https://nyc3.digitaloceanspaces.com',
    dir: 'backups'
  }
};
```
#### Usage
```typescript
import { Injectable } from '@nestjs/common';
import { DbBackupService } from 'zync-nest-library';
@Injectable()
export class MyService {
  constructor(private readonly backupService: DbBackupService) {}
  async createBackup() {
    await this.backupService.backup();
  }
  async scheduleBackups() {
    // Set up automated backups (runs every 6 hours by default)
    this.backupService.startBackupSchedule();
  }
}
```
### Upload Service
The `UploadService` handles file uploads with automatic image resizing and cloud storage integration.
#### Interfaces
```typescript
import { IUpload, IUploadResult } from 'zync-nest-library';
// Upload interface
interface IUpload {
  type?: "base64" | "buffer";
  file: any;
  filepath?: string;
  filename: string;
  filetype: string;
  dir?: string;
  transformName?: boolean;
}
// Upload result
interface IUploadResult {
  name: string;
  type: string;
  uri: string;
  lgUri?: string;  // Large thumbnail
  mdUri?: string;  // Medium thumbnail
  smUri?: string;  // Small thumbnail
}
```
#### Usage
```typescript
import { Injectable } from '@nestjs/common';
import { UploadService } from 'zync-nest-library';
@Injectable()
export class FileService {
  constructor(private readonly uploadService: UploadService) {}
  async uploadFile(file: Express.Multer.File): Promise<IUploadResult> {
    const uploadData: IUpload = {
      type: 'buffer',
      file: file.buffer,
      filename: file.originalname,
      filetype: file.mimetype,
      dir: 'uploads',
      transformName: true
    };
    return await this.uploadService.uploadFile(uploadData);
  }
  async uploadBase64Image(base64: string): Promise<IUploadResult> {
    const uploadData: IUpload = {
      type: 'base64',
      file: base64,
      filename: 'image.jpg',
      filetype: 'image/jpeg',
      dir: 'images'
    };
    return await this.uploadService.uploadFile(uploadData);
  }
}
```
### Bucket Service
The `BucketService` provides direct integration with cloud storage services (AWS S3, DigitalOcean Spaces).
#### Configuration
```typescript
// In your environment or config
export default () => ({
  bucket: {
    name: process.env.aws_bucket,
    region: process.env.aws_s3_region,
    key: process.env.aws_access_key_id,
    secret: process.env.aws_secret_access_key,
    endpoint: process.env.aws_s3_endpoint,
  }
});
```
#### Usage
```typescript
import { Injectable } from '@nestjs/common';
import { BucketService } from 'zync-nest-library';
@Injectable()
export class CloudStorageService {
  constructor(private readonly bucketService: BucketService) {}
  async uploadToBucket(buffer: Buffer, key: string) {
    return await this.bucketService.upload(buffer, key);
  }
  async downloadFromBucket(key: string) {
    return await this.bucketService.download(key);
  }
  async deleteFromBucket(key: string) {
    return await this.bucketService.delete(key);
  }
}
```
### Firebase Service
The `FirebaseService` provides push notification functionality using Firebase Cloud Messaging (FCM).
#### Configuration
First, you need to set up Firebase Admin SDK with a service account key:
1. Download your Firebase service account key JSON file
2. Place it in your project root as `serviceAccount.json`
3. The service will automatically initialize Firebase Admin SDK
#### Interfaces
```typescript
import { INotification } from 'zync-nest-library';
interface INotification {
  title: string;
  body: string;
  topic?: string;
  image?: string;
  data?: {
    type: "ORDER" | "SCHEME" | "RATE" | "PUSH" | "FEED";
    [x: string]: string;
  };
}
```
#### Usage
```typescript
import { Injectable } from '@nestjs/common';
import { FirebaseService, INotification } from 'zync-nest-library';
@Injectable()
export class NotificationService {
  constructor(private readonly firebaseService: FirebaseService) {}
  async sendToDevices(tokens: string[], notification: INotification) {
    await this.firebaseService.sendPushNotification(tokens, notification);
  }
  async sendToTopic(topic: string, notification: INotification) {
    await this.firebaseService.sendPushNotificationToTopic(topic, notification);
  }
  async subscribeToTopic(topic: string, tokens: string[]) {
    await this.firebaseService.subscribeToTopic(topic, tokens);
  }
}
```
### Mailer Service
The `MailerService` provides email sending functionality with template support.
#### Configuration
```typescript
import { IMailerConfig } from 'zync-nest-library';
const mailerConfig: IMailerConfig = {
  logo: 'https://example.com/logo.png',
  host: 'smtp.gmail.com',
  user: 'your-email@gmail.com',
  pass: 'your-app-password',
  from: 'noreply@yourcompany.com',
  port: '587',
  playStore: 'https://play.google.com/store/apps/details?id=your.app',
  appStore: 'https://apps.apple.com/app/your-app/id123456789'
};
```
#### Environment Variables
```env
# Email Configuration
MAILER_HOST=smtp.gmail.com
MAILER_USER=your-email@gmail.com
MAILER_PASS=your-app-password
MAILER_FROM=noreply@yourcompany.com
MAILER_PORT=587
MAILER_LOGO=https://example.com/logo.png
MAILER_PLAY_STORE=https://play.google.com/store/apps/details?id=your.app
MAILER_APP_STORE=https://apps.apple.com/app/your-app/id123456789
```
#### Usage
```typescript
import { Injectable } from '@nestjs/common';
import { MailerService, IMail } from 'zync-nest-library';
@Injectable()
export class EmailService {
  constructor(private readonly mailerService: MailerService) {}
  async sendEmail(mailData: IMail) {
    await this.mailerService.sendMail(mailData);
  }
  async sendWelcomeEmail(email: string, name: string) {
    const mailData: IMail = {
      to: email,
      subject: 'Welcome to Our Platform',
      template: 'welcome',
      context: {
        name: name,
        loginUrl: 'https://yourapp.com/login'
      }
    };
    
    await this.mailerService.sendMail(mailData);
  }
}
```
### Exabytes SMS Service
The Exabytes SMS service provides SMS sending functionality via Exabytes API.
#### Configuration
Configure the Exabytes SMS service using environment variables:
```env
# Exabytes SMS Configuration
exabytes_sms_username=your_username
exabytes_sms_password=your_password
exabytes_sms_url=https://sms.exabytes.com/api/send
exabytes_sms_sendid=YOUR_SENDER_ID
```
#### Usage
The Exabytes SMS service is typically used through the unified Message Service for SMS functionality.
### UltraMsg Service
The `UltraMsgService` provides WhatsApp messaging functionality via UltraMsg API.
#### Configuration
Configure the UltraMsg service using environment variables:
```env
# UltraMsg Configuration
ultramsg_instance=your_instance_id
ultramsg_token=your_api_token
ultramsg_url=https://api.ultramsg.com
```
#### Usage
```typescript
import { Injectable } from '@nestjs/common';
import { UltraMsgService } from 'zync-nest-library';
@Injectable()
export class WhatsAppService {
  constructor(private readonly ultraMsgService: UltraMsgService) {}
  async sendMessage(phone: string, message: string) {
    return await this.ultraMsgService.sendMessage(phone, message);
  }
  async sendDocument(phone: string, document: string, caption?: string) {
    return await this.ultraMsgService.sendDocument(phone, document, caption);
  }
}
```
### Message Service
The `MessageService` provides a unified interface for sending messages across different channels (Email, SMS, WhatsApp, Push Notifications).
#### Usage
```typescript
import { Injectable } from '@nestjs/common';
import { MessageService } from 'zync-nest-library';
@Injectable()
export class UnifiedMessageService {
  constructor(private readonly messageService: MessageService) {}
  async sendMultiChannelMessage(
    email: string,
    phone: string,
    pushTokens: string[],
    message: any
  ) {
    // Send via email
    await this.messageService.sendEmail({
      to: email,
      subject: message.subject,
      template: message.template,
      context: message.context
    });
    // Send via SMS (if configured)
    // await this.messageService.sendSMS(phone, message.text);
    // Send via WhatsApp (if configured)
    // await this.messageService.sendWhatsApp(phone, message.text);
    // Send push notification
    await this.messageService.sendPushNotification(pushTokens, {
      title: message.title,
      body: message.body,
      data: message.data
    });
  }
}
```
### Utility Functions
The library includes various utility functions for common operations:
```typescript
import {
  DateUtils,
  mkdir,
  uuidFilenameTransform,
  bufferFromBase64,
  getBase64FileName,
  toSlug,
  fileDownloadResponse
} from 'zync-nest-library';
// Date utilities
const timestamp = DateUtils.formatStringDate('25/12/2023');
// File utilities
const uniqueFilename = uuidFilenameTransform('image.jpg'); // Returns: uuid.jpg
const buffer = bufferFromBase64('data:image/jpeg;base64,...');
const filename = getBase64FileName('data:image/jpeg;base64,...'); // Returns: uuid.jpeg
// String utilities
const slug = toSlug('My Product Title'); // Returns: my-product-title-abc123
// Directory creation
mkdir('./uploads/images');
// File download response (Express)
fileDownloadResponse(res, buffer, 'report', 'pdf');
```
## 🔧 Configuration
### Environment Variables
```env
# Cloud Storage (DigitalOcean Spaces / AWS S3)
#-----------------s3-----------------#
aws_access_key_id=xxxx
aws_secret_access_key=xxxxx
aws_s3_region=nyc3
aws_s3_endpoint=https://xxxx.nyc3.digitaloceanspaces.com
aws_bucket=xxxx
aws_base_key=development
# Email Configuration (Mailer Service)
#-----------------mailer-----------------#
MAILER_HOST=smtp.gmail.com
MAILER_USER=your-email@gmail.com
MAILER_PASS=your-app-password
MAILER_FROM=noreply@yourcompany.com
MAILER_PORT=587
MAILER_LOGO=https://example.com/logo.png
MAILER_PLAY_STORE=https://play.google.com/store/apps/details?id=your.app
MAILER_APP_STORE=https://apps.apple.com/app/your-app/id123456789
# Exabytes SMS Configuration
#-----------------exabytes-----------------#
exabytes_sms_username=your_username
exabytes_sms_password=your_password
exabytes_sms_url=https://sms.exabytes.com/api/send
exabytes_sms_sendid=YOUR_SENDER_ID
# UltraMsg WhatsApp Configuration
#-----------------ultramsg-----------------#
ultramsg_instance=your_instance_id
ultramsg_token=your_api_token
ultramsg_url=https://api.ultramsg.com
# Firebase Configuration
#-----------------firebase-----------------#
# Note: Firebase requires a service account JSON file
# Place your serviceAccount.json file in the project root
# Download from: Firebase Console > Project Settings > Service Accounts
```
## 🛠️ Development
### Scripts
```bash
# Build the library
pnpm run build
# Build in watch mode
pnpm run build:watch
# Clean build artifacts
pnpm run clean
# Build and clean
pnpm run clean && pnpm run build
```
### Project Structure
```
libs/
├── src/
│   ├── dbbackup/          # Database backup functionality
│   │   ├── backup.config.ts
│   │   ├── backup.interface.ts
│   │   ├── backup.module.ts
│   │   └── backup.service.ts
│   ├── upload/            # File upload functionality
│   │   ├── bucket/        # Cloud storage integration
│   │   ├── upload.interface.ts
│   │   ├── upload.module.ts
│   │   ├── upload.service.ts
│   │   └── upload.utils.ts
│   ├── firebase/          # Firebase push notifications
│   │   ├── firebase.interface.ts
│   │   ├── firebase.module.ts
│   │   └── firebase.service.ts
│   ├── mailer/            # Email service
│   │   ├── mailer.interface.ts
│   │   ├── mailer.module.ts
│   │   └── mailer.service.ts
│   ├── message/           # Unified messaging service
│   │   ├── message.module.ts
│   │   └── message.service.ts
│   ├── exabytes/          # SMS service via Exabytes
│   │   ├── exabytes.config.ts
│   │   ├── exabytes.interface.ts
│   │   ├── exabytes.module.ts
│   │   └── exabytes.service.ts
│   ├── ultramsg/          # WhatsApp service via UltraMsg
│   │   ├── ultramsg.config.ts
│   │   ├── ultramsg.interface.ts
│   │   ├── ultramsg.module.ts
│   │   └── ultramsg.service.ts
│   ├── utils/             # Utility functions
│   │   ├── date.ts
│   │   ├── object.ts
│   │   └── index.ts
│   └── index.ts           # Main exports
└── tsconfig.lib.json
```
### Common Issues
#### 1. pnpm link not working
If `pnpm link` doesn't work, use the file path dependency method instead:
```json
{
  "dependencies": {
    "zync-nest-library": "file:../../zync-library/zync-nest-library"
  }
}
```
#### 2. Peer dependency warnings
If you see peer dependency warnings (e.g., `@nestjs/core` version mismatch), you can:
- Update your project's NestJS version to match
- Or add to your `package.json`:
```json
{
  "pnpm": {
    "peerDependencyRules": {
      "ignoreMissing": ["@nestjs/core"]
    }
  }
}
```
#### 3. Build errors after linking
Make sure to build the library first:
```bash
cd zync-nest-library
pnpm run build
```
#### 4. Changes not reflected
After making changes to the library:
```bash
# In library directory
pnpm run build
# No need to reinstall - changes are automatically available in linked projects
```
## 🐛 Issues
If you encounter any issues or have questions, please file an issue on the project repository.