zync-nest-fb-module
v1.0.17
Published
NestJS Facebook module with Facebook API utilities
Maintainers
Readme
Zync NestJS Facebook Library
A comprehensive NestJS library providing Facebook Graph API integration for WhatsApp messaging and template management.
📦 Features
- Facebook API Integration: Core service for Facebook Graph API requests
- WhatsApp Messaging: Send WhatsApp messages via Facebook Graph API
- Access Token Management: Automatic token refresh and management
- Template Management: Sync and manage WhatsApp message templates
- GraphQL Support: Full GraphQL integration for templates
- Type Safety: Full TypeScript support with interfaces and DTOs
🚀 Installation
Local Development
# Clone the repository
git clone https://github.com/zynctech/zync-nest-fb-module.git
cd zync-nest-fb-module
# Install dependencies
pnpm install
# Build the library
pnpm run buildUsing in Other Projects
Method 1: File Path Dependency (Recommended for pnpm)
In your project's package.json:
{
"dependencies": {
"zync-nest-fb-module": "file:../../zync-library/zync-nest-fb-library"
}
}Then run:
pnpm installMethod 2: npm link (For npm users)
# In the library directory
npm link
# In your consuming project
npm link zync-nest-fb-moduleMethod 3: pnpm link (Alternative for pnpm)
# 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-fb-module📋 Peer Dependencies
This library uses peer dependencies to avoid version conflicts with your project. This means you must install the following packages in your consuming project:
Required Peer Dependencies
pnpm add @nestjs/common@^11.1.6 @nestjs/core@^11.1.6 @nestjs/config@^4.0.2 @nestjs/axios@^4.0.1 @nestjs/mongoose@^11.0.3 @nestjs/graphql@^13.1.0 axios@^1.11.0 mongoose@^8.19.2 graphql@^16.11.0 moment@^2.30.1 rxjs@^7.8.2Or for npm:
npm install @nestjs/common@^11.1.6 @nestjs/core@^11.1.6 @nestjs/config@^4.0.2 @nestjs/axios@^4.0.1 @nestjs/mongoose@^11.0.3 @nestjs/graphql@^13.1.0 axios@^1.11.0 mongoose@^8.19.2 graphql@^16.11.0 moment@^2.30.1 rxjs@^7.8.2This ensures that:
- Your project uses its own versions of these packages
- There are no duplicate dependencies
- No version conflicts between your project and the library
- Smaller bundle size
📚 Usage
Basic Setup
Import the required modules in your NestJS application:
import { Module } from '@nestjs/common';
import { FacebookModule } from 'zync-nest-fb-module';
@Module({
imports: [
FacebookModule,
// ... other modules
],
})
export class AppModule {}Facebook Service
The FbService provides core functionality for Facebook Graph API integration.
Configuration
// In your environment or config
export default () => ({
facebook: {
appId: process.env.facebook_app_id,
appSecret: process.env.facebook_app_secret,
apiEndpoint: process.env.facebook_api_endpoint,
whatsappBusinessId: process.env.facebook_whatsapp_business_id,
whatsappPhoneNumberId: process.env.facebook_whatsapp_phone_number_id,
}
});Environment Variables
# Facebook Configuration
facebook_app_id=your_app_id
facebook_app_secret=your_app_secret
facebook_api_endpoint=https://graph.facebook.com/v22.0
facebook_whatsapp_business_id=your_business_account_id
facebook_whatsapp_phone_number_id=your_phone_number_id
facebook_access_token=your_long_lived_access_tokenUsage
import { Injectable } from '@nestjs/common';
import { FbService } from 'zync-nest-fb-module';
@Injectable()
export class MyService {
constructor(private readonly fbService: FbService) {}
async getWhatsAppTemplates() {
return await this.fbService.get({
type: "whatsapp",
accessToken: "your_access_token",
endpoint: "message_templates"
});
}
async sendWhatsAppMessage() {
return await this.fbService.post({
type: "whatsapp_message",
accessToken: "your_access_token",
body: {
messaging_product: "whatsapp",
to: "1234567890",
type: "template",
template: {
name: "your_template_name",
language: { code: "en" }
}
},
endpoint: "messages"
});
}
}Access Token Service
The FbAccessTokenService manages Facebook access tokens with automatic refresh.
Usage
import { Injectable } from '@nestjs/common';
import { FbAccessTokenService } from 'zync-nest-fb-module';
@Injectable()
export class TokenService {
constructor(private readonly tokenService: FbAccessTokenService) {}
async getAccessToken() {
// Returns the latest access token
return await this.tokenService.getToken();
}
async refreshAccessToken() {
// Manually refresh the access token
// This is automatically called when token is close to expiry
await await this.tokenService.refreshToken();
}
}Note: The access token is automatically refreshed when it's within 5 days of expiry.
Message Service
The FbMessageService provides high-level WhatsApp messaging functionality.
Interfaces
interface IFbWhatsAppMessagePayload {
to: string;
name: string;
language?: string;
}Usage
import { Injectable } from '@nestjs/common';
import { FbMessageService } from 'zync-nest-fb-module';
@Injectable()
export class WhatsAppService {
constructor(private readonly messageService: FbMessageService) {}
async sendMessage(phoneNumber: string, templateName: string) {
const result = await this.messageService.sendWhatsAppMessage({
to: phoneNumber,
name: templateName,
language: "en"
});
return {
messageId: result._id,
sent: result.sent,
phoneNumber: result.senderPhoneNumber
};
}
}Template Service
The FbWhatsAppMessageTemplateService manages WhatsApp message templates.
Usage
import { Injectable } from '@nestjs/common';
import { FbWhatsAppMessageTemplateService } from 'zync-nest-fb-module';
@Injectable()
export class TemplateService {
constructor(private readonly templateService: FbWhatsAppMessageTemplateService) {}
async syncTemplates() {
// Syncs templates from Facebook to local database
await await this.templateService.syncTemplates();
}
async findTemplate(templateName: string) {
return await this.templateService.findOne({ name: templateName });
}
async getAllTemplates() {
return await this.templateService.findAll({});
}
}Note: Templates are automatically synced from Facebook on module initialization.
🔧 Configuration
Environment Variables
# Facebook Graph API Configuration
facebook_app_id=your_app_id
facebook_app_secret=your_app_secret
facebook_api_endpoint=https://graph.facebook.com/v22.0
facebook_whatsapp_business_id=your_whatsapp_business_account_id
facebook_whatsapp_phone_number_id=your_whatsapp_phone_number_id
facebook_access_token=your_long_lived_access_token
# MongoDB Configuration (for tokens and templates)
mongodb_uri=mongodb://localhost:27017/your_databaseFacebook Setup
- Create a Facebook App at Facebook Developers
- Add WhatsApp Business products to your app
- Get your Business Account ID and Phone Number ID
- Generate a long-lived access token
- Configure your environment variables
📖 API Endpoints
Health Check
GET /healthReturns:
{
"status": "ok",
"timestamp": "2024-01-01T00:00:00.000Z"
}Root
GET /Returns:
{
"message": "Zync Nest Facebook API",
"version": "1.0.23",
"endpoints": {
"docs": "/api",
"health": "/health"
}
}🛠️ Development
Scripts
# Build the library
pnpm run build
# Build in watch mode
pnpm run build:watch
# Clean build artifacts
pnpm run clean
# Clean and rebuild
pnpm run clean && pnpm run build
# Update library links
pnpm run update-links
# Start development server
pnpm run start:devProject Structure
src/
├── core/
│ └── facebook/
│ ├── fb.config.ts # Facebook configuration
│ ├── fb.interface.ts # TypeScript interfaces
│ ├── fb.module.ts # Core Facebook module
│ ├── fb.service.ts # Facebook Graph API service
│ └── index.ts
├── facebook/
│ ├── accessToken/
│ │ ├── accessToken.dto.ts # GraphQL DTOs
│ │ ├── accessToken.module.ts # Access token module
│ │ ├── accessToken.repository.ts
│ │ ├── accessToken.resolver.ts # GraphQL resolver
│ │ ├── accessToken.schema.ts # MongoDB schema
│ │ └── accessToken.service.ts
│ ├── message/
│ │ ├── message.interface.ts # Message interfaces
│ │ ├── message.module.ts
│ │ └── message.service.ts
│ ├── template/
│ │ ├── template.dto.ts # GraphQL DTOs
│ │ ├── template.module.ts
│ │ ├── template.repository.ts
│ │ ├── template.resolver.ts # GraphQL resolver
│ │ ├── template.schema.ts # MongoDB schema
│ │ ├── template.service.ts
│ │ └── template.utils.ts
│ └── facebook.module.ts # Main Facebook module
├── main.ts # Application entry point
└── ...Key Components
Facebook Module (FbModule)
- Core service for Facebook Graph API integration
- Provides
get(),post(), andgetToken()methods
Access Token Module (FbAccessTokenModule)
- Manages Facebook access tokens
- Automatically refreshes tokens when needed (within 5 days of expiry)
- Stores tokens in MongoDB
Message Module (FbMessageModule)
- High-level WhatsApp messaging service
- Handles message sending with templates
- Supports template parameters
Template Module (FbWhatsAppMessageTemplateModule)
- Syncs templates from Facebook
- Stores templates in local MongoDB
- Provides GraphQL API for template management
🔍 Common Issues
1. Token expiry
If your access token expires, update the facebook_access_token environment variable with a new long-lived token.
2. Template sync issues
Make sure your app has the necessary permissions:
whatsapp_business_messagingwhatsapp_business_management
3. Message sending failures
Check that:
- The template name exists and is approved
- The recipient phone number is registered with WhatsApp
- Your business account is verified
4. Build errors after linking
Make sure to build the library first:
cd zync-nest-fb-library
pnpm run build5. Changes not reflected
After making changes to the library:
# In library directory
pnpm run build
# No need to reinstall - changes are automatically available in linked projects📝 License
ISC
👥 Author
sabiridwan
🔗 Repository
https://github.com/zynctech/zync-nest-fb-module
🐛 Issues
If you encounter any issues or have questions, please file an issue on the project repository.
