NestJS library with database backup and file upload utilities
npm install zync-nest-libraryA comprehensive NestJS library providing database backup utilities, file upload services, and common utilities for modern web applications.
- 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
``bashClone the repository
git clone
cd zync-nest-library
$3
#### 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 linkIn 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 setupIn the library directory
pnpm link --globalIn your consuming project
pnpm link --global zync-nest-library
`š Usage
$3
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 {}
`$3
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();
}
}
`$3
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 {
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 {
const uploadData: IUpload = {
type: 'base64',
file: base64,
filename: 'image.jpg',
filetype: 'image/jpeg',
dir: 'images'
};
return await this.uploadService.uploadFile(uploadData);
}
}
`$3
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);
}
}
`$3
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);
}
}
`$3
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);
}
}
`$3
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.
$3
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);
}
}
`$3
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
});
}
}
`$3
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
$3
`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=developmentEmail 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/id123456789Exabytes 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_IDUltraMsg WhatsApp Configuration
#-----------------ultramsg-----------------#
ultramsg_instance=your_instance_id
ultramsg_token=your_api_token
ultramsg_url=https://api.ultramsg.comFirebase 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
$3
`bash
Build the library
pnpm run buildBuild in watch mode
pnpm run build:watchClean build artifacts
pnpm run cleanBuild and clean
pnpm run clean && pnpm run build
`$3
`
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
`
$3
#### 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 buildNo need to reinstall - changes are automatically available in linked projects
``If you encounter any issues or have questions, please file an issue on the project repository.