In NestJS, wrap PindoSMS in an injectable service so it can be shared across modules.
1
Set up environment variables
Install @nestjs/config and add your token to .env:
npm install @nestjs/config
.env
PINDO_API_TOKEN=your_api_token_here
Register ConfigModule in your root AppModule so the token is available throughout the application:
app.module.ts
import { Module } from '@nestjs/common';import { ConfigModule } from '@nestjs/config';@Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), ],})export class AppModule {}
2
Create the SMS service
Create a PindoSMSService that reads the token from ConfigService and exposes a sendSMS method:
pindo-sms.service.ts
import { Injectable } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { PindoSMS, SMSPayload } from 'pindo-sms';@Injectable()export class PindoSMSService { private readonly client: PindoSMS; constructor(private readonly config: ConfigService) { this.client = new PindoSMS(this.config.getOrThrow<string>('PINDO_API_TOKEN')); } async sendSMS(to: string, text: string, sender: string): Promise<any> { const payload: SMSPayload = { to, text, sender }; return this.client.sendSMS(payload); }}
3
Register the service in a module
Add PindoSMSService to the providers array of the module that needs it:
sms.module.ts
import { Module } from '@nestjs/common';import { PindoSMSService } from './pindo-sms.service';@Module({ providers: [PindoSMSService], exports: [PindoSMSService],})export class SmsModule {}
4
Inject and use the service
Inject PindoSMSService into any controller or service that needs to send messages:
notifications.controller.ts
import { Controller, Post, Body } from '@nestjs/common';import { PindoSMSService } from './pindo-sms.service';@Controller('notifications')export class NotificationsController { constructor(private readonly smsService: PindoSMSService) {} @Post('send') async send( @Body('to') to: string, @Body('message') message: string, ) { return this.smsService.sendSMS(to, message, 'MyApp'); }}
ConfigService.getOrThrow throws at startup if the environment variable is missing, giving you an early failure rather than a runtime error when the first SMS is sent.