Developer Quick-Start: Build production-ready SMS appointment reminders using MessageBird API, Node.js, NestJS, and PostgreSQL. Learn scheduling, validation, and deployment. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.
This guide walks you through creating a production-ready SMS appointment scheduling and reminder system using NestJS, Node.js, and the MessageBird API. You'll learn everything from initial project setup to deployment and monitoring.
Important Note (2024): MessageBird rebranded as "Bird" in February 2024. The existing MessageBird
APIs and SDKs remain fully functional and compatible with the new branding (Bird Legal Change
Notice, February 2024). This guide uses the messagebird npm package (v4.0.1, published January 25, 2023), which continues to work with Bird's
infrastructure. Find new API documentation at bird.com/api-reference, while legacy documentation remains at developers.messagebird.com.
Project Overview and Goals
Build a backend system that enables users (or other systems) to schedule appointments and automatically trigger SMS reminders via MessageBird at a set time before each appointment.
Problem Solved: Reduce no-shows for appointments by sending timely SMS reminders, improving operational efficiency and customer experience. Automate the reminder process, eliminating manual effort.
Technologies:
- Node.js: Runtime environment for your backend application. Use Node.js v20 LTS (maintenance support until April 30, 2026) or v22 LTS (entered LTS October 29, 2024, active support until October 21, 2025, maintenance until April 30, 2027) per the official Node.js release schedule.
- NestJS: Progressive Node.js framework for building efficient, reliable, and scalable server-side applications. Its modular architecture, dependency injection, and TypeScript support make it ideal for robust applications. Compatible with NestJS v10.x and v11.x (v11.0.0 released January 20, 2025).
- MessageBird (now Bird): Communications platform for sending SMS messages and validating phone numbers. The MessageBird Node.js SDK (v4.0.1) remains fully functional following the 2024 rebrand to Bird.
- TypeScript: Enhances JavaScript with static typing for better code quality and maintainability.
- PostgreSQL (Optional but Recommended): Powerful open-source relational database for persisting appointment data. Uses TypeORM as the Object-Relational Mapper (ORM).
- Docker: Containerizes the application for consistent development and deployment environments.
System Flow:
- A client sends a request to the NestJS API endpoint to schedule an appointment.
- The Controller receives the request, validating input using Data Transfer Objects (DTOs).
- The Controller calls the AppointmentService to handle the business logic.
- The AppointmentService validates the phone number using MessageBird Lookup.
- The AppointmentService (optionally) persists appointment details to the database (e.g., PostgreSQL via TypeORM).
- The AppointmentService uses the MessageBird SDK to schedule the SMS reminder via the MessageBird API.
- MessageBird sends the SMS at the scheduled time.
Prerequisites:
- Node.js LTS version (v20.x or v22.x recommended) and npm/yarn installed. Note: Node.js v18 reached End-of-Life on April 30, 2025 β upgrade to v20 or v22.
- A MessageBird account with API credentials (API Key). Following the 2024 rebrand to Bird, obtain API keys from the Bird Dashboard (formerly MessageBird Dashboard).
- Basic understanding of TypeScript and REST APIs.
- Access to a terminal or command prompt.
- (Optional) Docker and Docker Compose installed.
- (Optional) PostgreSQL database running locally or accessible.
Final Outcome: A robust NestJS application with an API endpoint to schedule appointments, validate phone numbers, store appointment data, and reliably schedule SMS reminders via MessageBird.
1. Setting up the Project
Initialize your NestJS project and install the necessary dependencies.
- Install NestJS CLI: If you don't have the NestJS CLI installed globally, run:
npm install -g @nestjs/cli
- Create New NestJS Project:
nest new nestjs-messagebird-reminders
cd nestjs-messagebird-reminders
Choose your preferred package manager (npm or yarn) when prompted.
- Install Dependencies: Install modules for configuration, validation, MessageBird integration, and database operations (if using one).
npm install @nestjs/config class-validator class-transformer dotenv
npm install messagebird
npm install date-fns
npm install @nestjs/typeorm typeorm pg
- @nestjs/config: Manages environment variables.
- class-validator, class-transformer: Validate request DTOs.
- dotenv: Loads environment variables from a .env file.
- messagebird: Official Node.js SDK for the MessageBird API (v4.0.1, January 25, 2023). Despite being published in 2023, it remains fully functional with Bird's current infrastructure.
- date-fns: Modern library for date manipulation.
- @nestjs/typeorm, typeorm, pg: PostgreSQL integration via TypeORM.
- @nestjs/schedule: Useful for internal application scheduling, distinct from MessageBird's SMS scheduling.
- Environment Configuration (
.env): Create a.envfile in your project root:
.env
# .env
PORT=3000
# MessageBird Credentials & Settings (Bird as of Feb 2024)
MESSAGEBIRD_API_KEY=YOUR_LIVE_OR_TEST_API_KEY
MESSAGEBIRD_ORIGINATOR=YourAppName # Or your MessageBird phone number
MESSAGEBIRD_LOOKUP_COUNTRY_CODE=US # Default country code for Lookup API (ISO 3166-1 alpha-2)
REMINDER_HOURS_BEFORE=3 # Hours before appointment to send reminder
# Database (Optional β Example for PostgreSQL)
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=your_db_password
DB_DATABASE=reminders
NODE_ENV=development # Set to 'production' in production environments
MESSAGEBIRD_API_KEY: Obtain this from your Bird Dashboard (formerly MessageBird Dashboard: Developers β API access β Show key). Use a live key for real messages or a test key for development without sending actual SMS. API keys created before the February 2024 rebrand remain valid.MESSAGEBIRD_ORIGINATOR: The sender ID displayed on the recipient's phone. Use an alphanumeric string (max 11 chars, country restrictions apply) or a purchased MessageBird/Bird virtual mobile number (required for some countries like the US). Check Bird documentation for country-specific restrictions.MESSAGEBIRD_LOOKUP_COUNTRY_CODE: Helps the Lookup API parse numbers entered without a country code (use ISO 3166-1 alpha-2 format).REMINDER_HOURS_BEFORE: Configures the reminder timing.- Database Variables: Adjust these if you're using a database.
NODE_ENV: Important for TypeORM configuration (see Section 6).
- Load Configuration (
app.module.ts): Configure theConfigModuleto load the.envfile.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AppointmentModule } from './appointment/appointment.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
AppointmentModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- Enable Validation Pipe (
main.ts): Enable the global validation pipe to automatically validate incoming request bodies based on DTOs.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const port = configService.get<number>('PORT') || 3000;
app.useGlobalPipes(new ValidationPipe({
whitelist: true,
transform: true,
forbidNonWhitelisted: true,
}));
await app.listen(port);
console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
- Project Structure: NestJS encourages a modular structure. We'll create an
AppointmentModuleto encapsulate all appointment-related logic.
nest g module appointment
nest g controller appointment --no-spec
nest g service appointment --no-spec
This creates:
- src/appointment/appointment.module.ts
- src/appointment/appointment.controller.ts
- src/appointment/appointment.service.ts
Create a DTO directory: mkdir src/appointment/dto
2. Implementing Core Functionality (Scheduling Logic)
Implement the service responsible for validating data, interacting with MessageBird, and (optionally) saving to the database.
- Define Appointment DTO (
create-appointment.dto.ts): Create a Data Transfer Object to define the expected shape and validation rules for incoming request bodies.
import {
IsString,
IsNotEmpty,
IsPhoneNumber,
IsDateString,
MinLength,
IsISO8601,
} from 'class-validator';
export class CreateAppointmentDto {
@IsString()
@IsNotEmpty()
@MinLength(2)
customerName: string;
@IsPhoneNumber(null)
@IsNotEmpty()
phoneNumber: string;
@IsString()
@IsNotEmpty()
treatment: string;
@IsISO8601({ strict: true }, { message: 'appointmentTime must be a valid ISO 8601 date string (e.g., 2025-12-31T14:30:00.000Z)'})
@IsNotEmpty()
appointmentTime: string;
}
- We use class-validator decorators to enforce rules.
- @IsPhoneNumber: Provides basic validation. See warning in the code comment about production readiness.
- @IsISO8601: Ensures the date uses the correct format. Using UTC is crucial for avoiding timezone issues.
- Implement
AppointmentService: This service will contain the core logic. Note: This version does not include database persistence (see Section 6 for the optional DB integration).
import { Injectable, Logger, BadRequestException, InternalServerErrorException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as MessageBird from 'messagebird';
import { CreateAppointmentDto } from './dto/create-appointment.dto';
import { subHours, isBefore, parseISO, formatISO } from 'date-fns';
type MessageBirdClient = ReturnType<typeof MessageBird>;
@Injectable()
export class AppointmentService {
private readonly logger = new Logger(AppointmentService.name);
private messagebird: MessageBirdClient;
private readonly apiKey: string;
private readonly originator: string;
private readonly countryCode: string;
private readonly reminderHoursBefore: number;
constructor(private configService: ConfigService) {
this.apiKey = this.configService.get<string>('MESSAGEBIRD_API_KEY');
this.originator = this.configService.get<string>('MESSAGEBIRD_ORIGINATOR');
this.countryCode = this.configService.get<string>('MESSAGEBIRD_LOOKUP_COUNTRY_CODE');
this.reminderHoursBefore = parseInt(this.configService.get<string>('REMINDER_HOURS_BEFORE', '3'), 10);
if (!this.apiKey || !this.originator) {
this.logger.error('MessageBird API Key or Originator not configured!');
throw new InternalServerErrorException('Messaging service configuration error.');
}
if (isNaN(this.reminderHoursBefore) || this.reminderHoursBefore <= 0) {
this.logger.warn(`Invalid REMINDER_HOURS_BEFORE value. Defaulting to 3.`);
this.reminderHoursBefore = 3;
}
this.messagebird = MessageBird(this.apiKey);
}
async scheduleAppointmentReminder(dto: CreateAppointmentDto): Promise<{ id: string; message: string }> {
this.logger.log(`Scheduling reminder for ${dto.customerName} at ${dto.appointmentTime}`);
const appointmentDateTime = parseISO(dto.appointmentTime);
const reminderDateTime = subHours(appointmentDateTime, this.reminderHoursBefore);
const now = new Date();
const minReminderTime = new Date(now.getTime() + 5 * 60000);
if (isBefore(reminderDateTime, minReminderTime)) {
this.logger.warn(`Failed scheduling: Reminder time ${formatISO(reminderDateTime)} is too soon.`);
throw new BadRequestException(`Appointment must be scheduled far enough in advance to allow for the ${this.reminderHoursBefore}-hour reminder (at least 5 minutes from now).`);
}
let validatedPhoneNumber: string;
try {
validatedPhoneNumber = await new Promise<string>((resolve, reject) => {
this.messagebird.lookup.read(dto.phoneNumber, this.countryCode, (err: any, response: any) => {
if (err) {
this.logger.error(`Lookup failed for partial number: ${err.errors?.[0]?.description || err.message}`, err.stack);
if (err.errors?.[0]?.code === 21) {
return reject(new BadRequestException('Invalid phone number format provided.'));
}
return reject(new InternalServerErrorException('Failed to validate phone number.'));
}
if (response.type !== 'mobile') {
this.logger.warn(`Lookup successful for partial number, but type is '${response.type}'.`);
return reject(new BadRequestException('The provided phone number must be a mobile number.'));
}
this.logger.log(`Lookup successful. Normalized number format obtained.`);
resolve(response.phoneNumber);
});
});
} catch (error) {
throw error;
}
const reminderBody = `${dto.customerName}, here's a reminder for your ${dto.treatment} appointment scheduled for ${formatISO(appointmentDateTime)}. See you soon!`;
const params = {
originator: this.originator,
recipients: [validatedPhoneNumber],
scheduledDatetime: formatISO(reminderDateTime),
body: reminderBody,
};
try {
const messageResponse = await new Promise<any>((resolve, reject) => {
this.messagebird.messages.create(params, (err: any, response: any) => {
if (err) {
this.logger.error(`Failed to schedule SMS: ${err.errors?.[0]?.description || err.message}`, err.stack);
return reject(new InternalServerErrorException('Failed to schedule SMS reminder.'));
}
this.logger.log(`SMS scheduled successfully. Message ID: ${response.id}`);
resolve(response);
});
});
return {
id: messageResponse.id,
message: `Appointment reminder scheduled successfully for ${dto.customerName}.`,
};
} catch (error) {
this.logger.error(`Error during SMS scheduling: ${error.message}`, error.stack);
throw new InternalServerErrorException('An error occurred while scheduling the appointment reminder.');
}
}
}
- Initialization: Reads config (including REMINDER\_HOURS\_BEFORE) and initializes MessageBird.
- Date Handling: Uses date-fns for parsing, calculation (subHours), and validation (isBefore).
- Lookup: Calls messagebird.lookup.read wrapped in a Promise, handles errors, checks for mobile type.
- Scheduling: Calls messagebird.messages.create with scheduledDatetime, wrapped in a Promise.
- Return Type: Returns Promise<{ id: string; message: string }> as database persistence is not included here.
- Error Handling: Uses NestJS exceptions and Logger.
3. Building the API Layer
Create the controller to expose an endpoint for scheduling appointments.
import { Controller, Post, Body, HttpCode, HttpStatus, Logger } from '@nestjs/common';
import { AppointmentService } from './appointment.service';
import { CreateAppointmentDto } from './dto/create-appointment.dto';
@Controller('appointments')
export class AppointmentController {
private readonly logger = new Logger(AppointmentController.name);
constructor(private readonly appointmentService: AppointmentService) {}
@Post('/schedule')
@HttpCode(HttpStatus.CREATED)
async scheduleReminder(@Body() createAppointmentDto: CreateAppointmentDto) {
this.logger.log(`Received request to schedule reminder for ${createAppointmentDto.customerName}`);
return this.appointmentService.scheduleAppointmentReminder(createAppointmentDto);
}
}
- Defines a POST endpoint at /appointments/schedule.
- Injects the validated CreateAppointmentDto using @Body().
- Sets the success status code to 201 Created.
- Delegates the core logic to the injected AppointmentService.
Testing the Endpoint (Example using curl):
Assuming your app runs on port 3000:
curl -X POST http://localhost:3000/appointments/schedule \
-H "Content-Type: application/json" \
-d '{
"customerName": "Jane Doe",
"phoneNumber": "+12025550154",
"treatment": "Consultation",
"appointmentTime": "2025-12-25T15:00:00.000Z"
}'
Note: Use a real mobile number for testing with live keys. The appointmentTime must be later
than the configured reminder hours plus a small buffer (e.g., 5 minutes) from the current time, specified in
UTC.
Expected Success Response (201 Created β without DB):
{
"id": "mb_message_id_string",
"message": "Appointment reminder scheduled successfully for Jane Doe."
}
Expected Error Response (400 Bad Request β e.g., invalid date):
{
"statusCode": 400,
"message": [
"appointmentTime must be a valid ISO 8601 date string (e.g., 2025-12-31T14:30:00.000Z)"
],
"error": "Bad Request"
}
4. Integrating with MessageBird (Deep Dive)
You've already initialized the client and used the Lookup and Messages APIs. Review key integration points:
- SDK Initialization: Done in AppointmentService constructor using MessageBird(this.apiKey).
- API Key Security: Handled via .env file and ConfigModule. Never commit your API key to version control. Use environment variables in deployment environments.
- Dashboard Configuration:
- API Key: Navigate to Bird Dashboard β Developers β API access (REST). Create a new key (choose "Live" or "Test") or copy an existing one. Store it securely.
- Required Permissions: Ensure the API key has permissions for "Lookup API access" and "Send SMS via API" (or similar wording in the dashboard).
- Originator: Consider purchasing a Virtual Mobile Number (VMN) from MessageBird (Numbers section) for better deliverability, especially in countries like the US/Canada that restrict alphanumeric senders. Configure this number or your chosen alphanumeric ID in MESSAGEBIRD\_ORIGINATOR.
- Lookup: The MESSAGEBIRD\_LOOKUP\_COUNTRY\_CODE in .env aids parsing numbers without a country code.
- Scheduled Messages: View scheduled (and sent) messages in the Bird Dashboard β SMS β Scheduled overview.
- Environment Variables: (Defined in Section 1)
- MESSAGEBIRD\_API\_KEY: Your secret key.
- MESSAGEBIRD\_ORIGINATOR: Sender ID.
- MESSAGEBIRD\_LOOKUP\_COUNTRY\_CODE: Default country for Lookup.
- REMINDER\_HOURS\_BEFORE: Reminder timing configuration.
- Fallback Mechanisms: The current implementation relies heavily on MessageBird. For critical systems, consider:
- Retries: Implement retries with exponential backoff for transient network errors (see Section 5).
- Monitoring & Alerting: Set up alerts for high failure rates (see Section 10).
- Secondary Provider (Advanced): Integrate a second SMS provider as a fallback (adds complexity).
5. Error Handling, Logging, and Retry Mechanisms
- Error Handling Strategy:
- Use standard NestJS HTTP exceptions (BadRequestException, InternalServerErrorException, etc.) thrown from the service layer.
- Validate input rigorously using DTOs and ValidationPipe.
- Catch specific MessageBird SDK errors (e.g., code 21 for invalid number) and map them appropriately.
- Log detailed errors server-side.
- Logging:
- Use the built-in Logger service (@nestjs/common).
- Log key events: request received, validation results, MessageBird API calls (start, success, failure), database operations (if used), final outcome.
- Include contextual information (e.g., customer name initial, appointment time).
- Security: Be extremely cautious about logging sensitive data. Do not log full phone numbers or API keys unless absolutely necessary and measures like masking or encryption are in place. Log partial identifiers or correlation IDs instead.
- Consider structured logging (JSON) for production environments.
- Retry Mechanisms:
- Lookup/Scheduling: For transient network issues, wrap the messagebird.lookup.read and
messagebird.messages.create promise calls with a retry mechanism. Use libraries like
async-retryor implement a simple loop with exponential backoff and jitter. Limit retry attempts.
import * as retry from 'async-retry';
try {
validatedPhoneNumber = await retry(async (bail, attempt) => {
this.logger.log(`Lookup attempt ${attempt}...`);
return new Promise<string>((resolve, reject) => {
this.messagebird.lookup.read(dto.phoneNumber, this.countryCode, (err: any, response: any) => {
if (err) {
if (err.errors?.[0]?.code === 21) {
bail(new BadRequestException('Invalid phone number format. Check the number and try again.'));
return;
}
return reject(err);
}
if (response.type !== 'mobile') {
bail(new BadRequestException('The phone number must be a mobile number, not a landline.'));
return;
}
resolve(response.phoneNumber);
});
});
}, {
retries: 3,
factor: 2,
minTimeout: 1000,
onRetry: (error, attempt) => {
this.logger.warn(`Lookup attempt ${attempt} failed. Retrying... Error: ${error.message}`);
}
});
} catch (error) {
this.logger.error(`Lookup failed permanently: ${error.message}`, error.stack);
if (error instanceof BadRequestException) throw error;
throw new InternalServerErrorException('Failed to validate phone number after multiple attempts. Please try again later.');
}
- Database: TypeORM handles some connection retries. Configure the connection pool robustly.
6. Database Schema and Data Layer (Optional: PostgreSQL + TypeORM)
This section details how to add database persistence using TypeORM and PostgreSQL. If you implement
this, you need to modify the AppointmentService and AppModule shown in previous
sections.
- Install Dependencies: (Should be done in Section 1)
Bash
- Configure
TypeOrmModule(app.module.ts): Modify yoursrc/app.module.tsto includeTypeOrmModule.
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AppointmentModule } from './appointment/appointment.module';
import { Appointment } from './appointment/entities/appointment.entity';
@Module({
imports: [
ConfigModule.forRoot({ }),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get<string>('DB_HOST'),
port: configService.get<number>('DB_PORT'),
username: configService.get<string>('DB_USERNAME'),
password: configService.get<string>('DB_PASSWORD'),
database: configService.get<string>('DB_DATABASE'),
entities: [Appointment],
synchronize: configService.get<string>('NODE_ENV') !== 'production',
}),
}),
AppointmentModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- CRITICAL: synchronize: true is for development only. In production, always use synchronize: false and manage schema changes via TypeORM migrations. Setting synchronize: true in production can cause data loss as TypeORM automatically syncs schema changes without validation.
- Define
AppointmentEntity: Create the entity file:mkdir src/appointment/entities
import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn, UpdateDateColumn } from 'typeorm';
export enum AppointmentStatus {
SCHEDULED = 'SCHEDULED',
SENT = 'SENT',
FAILED = 'FAILED',
CANCELLED = 'CANCELLED',
}
@Entity('appointments')
export class Appointment {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 100 })
customerName: string;
@Index()
@Column({ length: 20 })
phoneNumber: string;
@Column({ length: 100 })
treatment: string;
@Index()
@Column({ type: 'timestamp with time zone' })
appointmentTime: Date;
@Column({ type: 'timestamp with time zone' })
reminderTime: Date;
@Column({ nullable: true, length: 64 })
messagebirdMessageId?: string;
@Index()
@Column({
type: 'enum',
enum: AppointmentStatus,
default: AppointmentStatus.SCHEDULED,
})
status: AppointmentStatus;
@CreateDateColumn({ type: 'timestamp with time zone' })
createdAt: Date;
@UpdateDateColumn({ type: 'timestamp with time zone' })
updatedAt: Date;
}
- Inject Repository and Update Service:
- Import
TypeOrmModuleinAppointmentModule:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppointmentController } from './appointment.controller';
import { AppointmentService } from './appointment.service';
import { Appointment } from './entities/appointment.entity';
@Module({
imports: [TypeOrmModule.forFeature([Appointment])],
controllers: [AppointmentController],
providers: [AppointmentService],
})
export class AppointmentModule {}
- Inject Repository and Modify
AppointmentService: Updatesrc/appointment/appointment.service.tsto inject the repository and save the appointment. ThescheduleAppointmentRemindermethod needs modifications to include database persistence.
import { Injectable, Logger, BadRequestException, InternalServerErrorException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as MessageBird from 'messagebird';
import { CreateAppointmentDto } from './dto/create-appointment.dto';
import { subHours, isBefore, parseISO, formatISO } from 'date-fns';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Appointment, AppointmentStatus } from './entities/appointment.entity';
type MessageBirdClient = ReturnType<typeof MessageBird>;
@Injectable()
export class AppointmentService {
private readonly logger = new Logger(AppointmentService.name);
private messagebird: MessageBirdClient;
private readonly apiKey: string;
private readonly originator: string;
private readonly countryCode: string;
private readonly reminderHoursBefore: number;
constructor(
private configService: ConfigService,
@InjectRepository(Appointment)
private appointmentRepository: Repository<Appointment>,
) {
this.apiKey = this.configService.get<string>('MESSAGEBIRD_API_KEY');
this.originator = this.configService.get<string>('MESSAGEBIRD_ORIGINATOR');
this.countryCode = this.configService.get<string>('MESSAGEBIRD_LOOKUP_COUNTRY_CODE');
this.reminderHoursBefore = parseInt(this.configService.get<string>('REMINDER_HOURS_BEFORE', '3'), 10);
if (!this.apiKey || !this.originator) {
this.logger.error('MessageBird API Key or Originator not configured!');
throw new InternalServerErrorException('Messaging service configuration error.');
}
if (isNaN(this.reminderHoursBefore) || this.reminderHoursBefore <= 0) {
this.logger.warn(`Invalid REMINDER_HOURS_BEFORE value. Defaulting to 3.`);
this.reminderHoursBefore = 3;
}
this.messagebird = MessageBird(this.apiKey);
}
async scheduleAppointmentReminder(dto: CreateAppointmentDto): Promise<{ appointmentId: string; messagebirdMessageId: string; message: string }> {
this.logger.log(`Scheduling reminder for ${dto.customerName} at ${dto.appointmentTime}`);
const appointmentDateTime = parseISO(dto.appointmentTime);
const reminderDateTime = subHours(appointmentDateTime, this.reminderHoursBefore);
const now = new Date();
const minReminderTime = new Date(now.getTime() + 5 * 60000);
if (isBefore(reminderDateTime, minReminderTime)) {
this.logger.warn(`Failed scheduling: Reminder time ${formatISO(reminderDateTime)} is too soon.`);
throw new BadRequestException(`Appointment must be scheduled far enough in advance to allow for the ${this.reminderHoursBefore}-hour reminder (at least 5 minutes from now).`);
}
let validatedPhoneNumber: string;
try {
validatedPhoneNumber = await new Promise<string>((resolve, reject) => {
this.messagebird.lookup.read(dto.phoneNumber, this.countryCode, (err: any, response: any) => {
if (err) {
this.logger.error(`Lookup failed: ${err.errors?.[0]?.description || err.message}`, err.stack);
if (err.errors?.[0]?.code === 21) {
return reject(new BadRequestException('Invalid phone number format provided.'));
}
return reject(new InternalServerErrorException('Failed to validate phone number.'));
}
if (response.type !== 'mobile') {
this.logger.warn(`Lookup successful, but type is '${response.type}'.`);
return reject(new BadRequestException('The provided phone number must be a mobile number.'));
}
this.logger.log(`Lookup successful. Normalized number format obtained.`);
resolve(response.phoneNumber);
});
});
} catch (error) {
throw error;
}
const reminderBody = `${dto.customerName}, reminder for your ${dto.treatment} appointment at ${formatISO(appointmentDateTime)}. See you soon!`;
const params = {
originator: this.originator,
recipients: [validatedPhoneNumber],
scheduledDatetime: formatISO(reminderDateTime),
body: reminderBody,
};
try {
const messageResponse = await new Promise<any>((resolve, reject) => {
this.messagebird.messages.create(params, (err: any, response: any) => {
if (err) {
this.logger.error(`Failed to schedule SMS: ${err.errors?.[0]?.description || err.message}`, err.stack);
return reject(new InternalServerErrorException('Failed to schedule SMS reminder.'));
}
this.logger.log(`SMS scheduled successfully. Message ID: ${response.id}`);
resolve(response);
});
});
const appointment = this.appointmentRepository.create({
customerName: dto.customerName,
phoneNumber: validatedPhoneNumber,
treatment: dto.treatment,
appointmentTime: appointmentDateTime,
reminderTime: reminderDateTime,
messagebirdMessageId: messageResponse.id,
status: AppointmentStatus.SCHEDULED,
});
const savedAppointment = await this.appointmentRepository.save(appointment);
this.logger.log(`Appointment saved to database. ID: ${savedAppointment.id}`);
return {
appointmentId: savedAppointment.id,
messagebirdMessageId: messageResponse.id,
message: `Appointment reminder scheduled successfully for ${dto.customerName}.`,
};
} catch (error) {
this.logger.error(`Error during SMS scheduling: ${error.message}`, error.stack);
throw new InternalServerErrorException('An error occurred while scheduling the appointment reminder.');
}
}
}
This completes the database integration section. The service now persists appointments to PostgreSQL and returns both the database appointment ID and MessageBird message ID.
Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)
If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.
curl -X POST https://api.sendsmsnokyc.com/messages \
-H "x-api-key: $SMSROUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": ["+14155551234"],
"channel": ["sms"],
"body": "Your verification code is 482910"
}'
- Instant onboarding: No KYC paperwork or sales queues β grab an API key and fund with crypto (BTC/USDT) or card.
- Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
- Transparent global pricing: Compare exact per-country termination rates on our live pricing page.
Ship Global SMS in One API Call
Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.
Explore SMSRoute Developers β