0.0.30 • Published 4 months ago

@usemonitang/monita-libs v0.0.30

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

Monita Microservices Libraries

This directory contains shared libraries used across the Monita microservices architecture. Below is a guide on how to use each library in your services.

Cache Library (@/libs/cache)

Redis-based caching implementation for the microservices.

Environment Variables

Each service should have these Redis-related environment variables:

  • REDIS_HOST: Defaults to localhost
  • REDIS_PORT: Default to 6379
  • REDIS_USERNAME (Optional)
  • REDIS_PASSWORD (Optional)

Usage

import { CacheModule, CacheService } from '@/libs/cache';

@Module({
  imports: [
    CacheModule.register()
  ]
})

// In your service:
constructor(private readonly cacheService: CacheService) {}

// Basic cache operations
await this.cacheService.set('key', 'value', ttlSeconds);
const value = await this.cacheService.get('key');
await this.cacheService.del('key');

// Hash operations
await this.cacheService.hset('key', 'field', 'value');
const hashValue = await this.cacheService.hget('key', 'field');
const allValues = await this.cacheService.hgetall('key');

MonitaBaseAuthGuard

A base implementation of the auth guard to be used across each service in the system

Dependencies:

  • A JWT secret.

Basic Usage

import { MonitaBaseAuthGaurd } from '@usemonitang/monita-libs';

/**
 * Create your own auth guard extending the MonitaBaseAuthGuard. We
 * do this to put the MonitaBaseAuthGuard in the same context as the 
 * current NestJs application for better error capturing.
*/
export class AuthGuard extends MonitaBaseAuthGuard {
  constructor(
    private reflector: Reflector,
    private configService: ConfigService
  ) {
    super(reflector);
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const result = await super.canActivate(
      context,
      this.configService.get("JWT_SECRET") as string
    );
    return result;
  }
}

BullMQ Library (@/libs/bullmq)

Background job processing library for handling long-running tasks, retries, and scheduled jobs.

Usage

import { BullmqModule } from '@/libs/bullmq';
import { join } from 'path';

// Register in your module
@Module({
  imports: [
    BullmqModule.forFeature({
      queueName: 'my-queue',
      processorPath: join(__dirname, 'processors', 'my.processor.js'),
      concurrency: 3,
      defaultJobOptions: {
        attempts: 3,
        backoff: {
          type: 'exponential',
          delay: 1000,
        },
      },
    }),
  ],
})

// Create a job processor (my.processor.ts)
import { Job } from 'bullmq';

export default async function myProcessor(job: Job) {
  try {
    console.log(`Processing job ${job.id}`);
    await job.updateProgress(50);
    // Your job logic here
    return { processed: true };
  } catch (error) {
    console.error(`Error processing job ${job.id}:`, error);
    throw error;
  }
}

// In your service
@Injectable()
export class MyService {
  constructor(
    @Inject('BullQueue_my-queue')
    private myQueue: Queue,
  ) {}

  async addJob(data: any) {
    // Regular job
    await this.myQueue.add('job-name', data);

    // Delayed job
    await this.myQueue.add('delayed-job', data, {
      delay: 5000, // 5 seconds
    });

    // Repeatable job
    await this.myQueue.add('repeatable-job', data, {
      repeat: {
        every: 1000 * 60, // Every minute
      },
    });
  }
}

Features

  1. Queue Management: Create, pause, resume, and clean queues
  2. Job Processing: Handle long-running tasks with progress tracking
  3. Automatic Retries: Configure retry attempts and backoff strategies
  4. Job Scheduling: Delayed and repeatable jobs
  5. Event Handling: Monitor job completion and failures
  6. Resource Cleanup: Automatic cleanup on application shutdown

Environment Variables

# BullMQ Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_password

Notification Client

Shared utilities, constants, interfaces, and enums used across services.

Usage

import {
  NOTIFICATION_QUEUE,
  generateRandomString,
  formatPhoneNumber,
  OtpPurpose,
  SwaggerConfig,
} from '@/libs/common';

// Use constants
console.log(NOTIFICATION_QUEUE); // 'notification'

// Use utility functions
const randomStr = generateRandomString();
const formattedPhone = formatPhoneNumber('+2341234567890');

// Use enums and interfaces
const purpose: OtpPurpose = OtpPurpose.REGISTRATION;

Best Practices

  1. Always import from the library's main entry point (e.g., @/libs/auth not @/libs/auth/src/*)
  2. Use TypeScript types and interfaces provided by the libraries
  3. Follow the async/await pattern when working with services
  4. Configure modules properly in your service's root module
  5. Handle errors appropriately as most library functions are promise-based

Configuration

Most libraries require configuration through environment variables. Ensure these are set in your service's .env file:

# Cache Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_password

# NATS Configuration
NATS_URL=nats://localhost:4222
NATS_SERVICE_QUEUE=service_queue  # Replace 'service' with your service name (e.g., payment_queue)

# Other configurations...
0.0.30

4 months ago

0.0.29

4 months ago

0.0.26

5 months ago

0.0.27

5 months ago

0.0.28

4 months ago

0.0.20

5 months ago

0.0.21

5 months ago

0.0.22

5 months ago

0.0.23

5 months ago

0.0.24

5 months ago

0.0.25

5 months ago

0.0.15

5 months ago

0.0.16

5 months ago

0.0.17

5 months ago

0.0.18

5 months ago

0.0.19

5 months ago

0.0.10

5 months ago

0.0.11

5 months ago

0.0.12

5 months ago

0.0.13

5 months ago

0.0.14

5 months ago

0.0.9

5 months ago

0.0.8

5 months ago

0.0.7

5 months ago

0.0.5

5 months ago

0.0.4

5 months ago

0.0.3

5 months ago

0.0.2

5 months ago

0.0.1

5 months ago