### Install nestjs-sqs and AWS SDK Source: https://github.com/ssut/nestjs-sqs/blob/master/README.md Install the necessary packages for nestjs-sqs and the AWS SDK for SQS. ```shell npm i --save @ssut/nestjs-sqs @aws-sdk/client-sqs ``` -------------------------------- ### Comprehensive Async SQS Configuration Example Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md A complete example demonstrating `registerAsync` with `useFactory` for configuring multiple SQS consumers and producers, including advanced options like batch size, wait time, and stop options. ```typescript import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { SqsModule } from '@ssut/nestjs-sqs'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, }), SqsModule.registerAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ consumers: [ { name: 'order-events', queueUrl: configService.getOrThrow('SQS_ORDER_QUEUE_URL'), region: configService.get('AWS_REGION', 'us-east-1'), batchSize: configService.get('SQS_BATCH_SIZE', 10), waitTimeSeconds: configService.get('SQS_WAIT_TIME', 20), visibilityTimeout: 60, messageAttributeNames: ['All'], stopOptions: { emitStopEvent: true, }, }, { name: 'notification-events', queueUrl: configService.getOrThrow('SQS_NOTIFICATION_QUEUE_URL'), region: configService.get('AWS_REGION', 'us-east-1'), }, ], producers: [ { name: 'order-events', queueUrl: configService.getOrThrow('SQS_ORDER_QUEUE_URL'), region: configService.get('AWS_REGION', 'us-east-1'), batchSize: 10, batchDelayMs: 100, }, ], globalStopOptions: { emitStopEvent: true, }, }), inject: [ConfigService], }), ], }) export class AppModule {} ``` -------------------------------- ### Module Init Phase (OnModuleInit) Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Describes the initialization sequence executed when the NestJS application starts, including consumer and producer setup. ```mermaid 1. SqsService.onModuleInit() called by NestJS ↓ 2. DiscoveryService finds all @SqsMessageHandler methods ↓ 3. DiscoveryService finds all @SqsConsumerEventHandler methods ↓ 4. For each consumer config: a. Find matching @SqsMessageHandler b. Create Consumer instance with handler c. Attach event handlers via @SqsConsumerEventHandler d. Store Consumer in SqsService.consumers map ↓ 5. For each producer config: a. Create Producer instance b. Store Producer in SqsService.producers map ↓ 6. Call consumer.start() for all consumers ↓ 7. Consumers begin polling queues ``` -------------------------------- ### SqsModuleOptionsFactory Implementation Example Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/types.md Example implementation of SqsModuleOptionsFactory using NestJS ConfigService to provide SQS consumer and producer configurations. ```typescript import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { SqsModuleOptionsFactory, SqsOptions } from '@ssut/nestjs-sqs'; @Injectable() export class SqsConfigService implements SqsModuleOptionsFactory { constructor(private configService: ConfigService) {} async createOptions(): Promise { return { consumers: [ { name: 'my-consumer', queueUrl: this.configService.get('SQS_QUEUE_URL'), region: this.configService.get('AWS_REGION'), }, ], producers: [ { name: 'my-producer', queueUrl: this.configService.get('SQS_QUEUE_URL'), region: this.configService.get('AWS_REGION'), }, ], }; } } ``` -------------------------------- ### Configure SQS Consumer with Advanced Options Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Example showing detailed configuration for an SQS consumer, including polling behavior, message handling, and graceful shutdown. ```typescript SqsModule.register({ consumers: [ { name: 'order-events', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/orders.fifo', region: 'us-east-1', // Polling behavior batchSize: 10, waitTimeSeconds: 20, visibilityTimeout: 60, // Handler has 60 seconds to complete // Message handling messageAttributeNames: ['All'], terminateVisibilityTimeout: true, // Graceful shutdown stopOptions: { emitStopEvent: true, }, }, ], }) ``` -------------------------------- ### Register Module with Consumers and Producers Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Minimal example demonstrating how to register the SqsModule with both consumer and producer configurations. ```typescript SqsModule.register({ consumers: [ { name: 'order-queue', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/orders.fifo', }, ], producers: [ { name: 'order-queue', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/orders.fifo', }, ], }) ``` -------------------------------- ### Message Usage Examples Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/types.md Illustrates how to construct Message objects for simple and FIFO queues. Ensure correct fields are provided based on queue type. ```typescript // Simple message const msg: Message<{ orderId: string }> = { id: '123', body: { orderId: 'ORD-001' }, }; // FIFO queue message const fifoMsg: Message = { id: 'msg-1', body: { data: 'content' }, groupId: 'order-group', deduplicationId: 'msg-1', delaySeconds: 5, }; ``` -------------------------------- ### Producer Configuration Example Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Configure individual message producers with options like name, queue URL, region, batching, and FIFO queue functions. ```typescript SqsModule.register({ producers: [ { name: 'order-events', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/orders.fifo', region: 'us-east-1', // Batching batchSize: 10, batchDelayMs: 100, // Send after 100ms even if batch not full // FIFO queue generation functions messageDedupIdFn: (msg) => msg.id, messageGroupIdFn: (msg) => msg.groupId, }, ], }) ``` -------------------------------- ### Example: Error Handling with SqsConsumerEventHandler Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/Decorators.md Demonstrates how to use `@SqsConsumerEventHandler` to catch and handle processing errors for SQS messages. Includes setup with `@SqsMessageHandler` and logging. ```typescript import { Injectable, Logger } from '@nestjs/common'; import { Message } from '@aws-sdk/client-sqs'; import { SqsConsumerEventHandler, SqsMessageHandler } from '@ssut/nestjs-sqs'; @Injectable() export class UserEventProcessor { private logger = new Logger(UserEventProcessor.name); @SqsMessageHandler('user-events') async handleUserEvent(message: Message) { const event = JSON.parse(message.Body); // Process user event this.processEvent(event); } @SqsConsumerEventHandler('user-events', 'processing_error') async handleProcessingError(error: Error, message: Message) { this.logger.error( `Failed to process message: ${error.message}`, error.stack ); // Send to DLQ, alert monitoring, etc. await this.reportError(error, message); } private async reportError(error: Error, message: Message) { // Implementation for error reporting } private processEvent(event: any) { // Implementation } } ``` -------------------------------- ### Custom Configuration Service with SqsModuleOptionsFactory Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Implement `SqsModuleOptionsFactory` to create complex configuration logic for SQS consumers and producers. This example shows how to inject `ConfigService` to retrieve SQS-related settings. ```typescript import { Injectable } from '@nestjs/common'; import { SqsModuleOptionsFactory, SqsOptions } from '@ssut/nestjs-sqs'; @Injectable() export class SqsConfigService implements SqsModuleOptionsFactory { constructor(private configService: ConfigService) {} async createOptions(): Promise { const baseUrl = this.configService.get('SQS_BASE_URL'); const region = this.configService.get('AWS_REGION'); return { consumers: [ { name: 'orders', queueUrl: `${baseUrl}/orders`, region, }, { name: 'notifications', queueUrl: `${baseUrl}/notifications`, region, }, ], producers: [ { name: 'orders', queueUrl: `${baseUrl}/orders`, region, }, ], logger: this.createCustomLogger(), }; } private createCustomLogger() { // Return custom logger } } @Module({ imports: [ SqsModule.registerAsync({ useClass: SqsConfigService, }), ], }) export class AppModule {} ``` -------------------------------- ### Global Module Registration Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Example of registering `SqsModule` as a global module using the `@Global()` decorator. ```typescript @Global() @Module({ imports: [DiscoveryModule], providers: [SqsService], exports: [SqsService], }) export class SqsModule {} ``` -------------------------------- ### Generic Message Typing Example Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Demonstrates how to use generic types with `Message` for type-safe message bodies and how to parse them in handlers. ```typescript // Type-safe message bodies const message: Message = { id: '1', body: { ... }, // Must match OrderData type }; // Receive typed messages function handleOrder(message: Message) { const order = JSON.parse(message.Body) as OrderData; } ``` -------------------------------- ### Register SQS Module Async with Factory Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsModule.md Use registerAsync with a factory function to provide SQS module configuration asynchronously. This example demonstrates injecting ConfigService to resolve environment variables for queue URLs and regions. ```typescript import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { SqsModule } from '@ssut/nestjs-sqs'; @Module({ imports: [ ConfigModule.forRoot(), SqsModule.registerAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => { return { consumers: [ { name: 'myConsumer', queueUrl: configService.get('SQS_QUEUE_URL'), region: configService.get('AWS_REGION'), }, ], producers: [ { name: 'myProducer', queueUrl: configService.get('SQS_QUEUE_URL'), region: configService.get('AWS_REGION'), }, ], }; }, inject: [ConfigService], }), ], }) export class AppModule {} ``` -------------------------------- ### Example: Multiple Event Handlers with SqsConsumerEventHandler Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/Decorators.md Shows how to attach multiple `@SqsConsumerEventHandler` decorators to a single class to manage different types of SQS consumer events like processing errors, timeouts, and empty queues. ```typescript @Injectable() export class QueueMonitor { private logger = new Logger(QueueMonitor.name); @SqsConsumerEventHandler('data-sync', 'processing_error') async onProcessingError(error: Error, message: Message) { this.logger.error(`Data sync error: ${error.message}`); } @SqsConsumerEventHandler('data-sync', 'timeout_error') async onTimeout(error: Error) { this.logger.warn('Data sync handler timed out'); } @SqsConsumerEventHandler('data-sync', 'empty') async onQueueEmpty() { this.logger.debug('Data sync queue is empty'); } @SqsConsumerEventHandler('data-sync', 'error') async onSQSError(error: Error) { this.logger.error(`SQS API error: ${error.message}`); } } ``` -------------------------------- ### Sending a Single Message with SqsService Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsService.md Shows how to send a single message to an SQS queue using the `send` method of SqsService. This example includes message ID, body, and FIFO-specific group and deduplication IDs. ```typescript async submitOrder(orderId: string, items: any[]) { await this.sqsService.send('order-queue', { id: orderId, body: { orderId, items, timestamp: new Date().toISOString(), }, groupId: orderId, // For FIFO queues deduplicationId: orderId, }); } ``` -------------------------------- ### Project Directory Structure Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/INDEX.md Overview of the project's file organization, highlighting key documentation and API reference files. ```bash Project: /ssut/nestjs-sqs Content: # Documentation Index Complete technical reference for `@ssut/nestjs-sqs` v3.0.1 ## Quick Start - **[README.md](./README.md)** — Project overview, features, complete example, and common patterns - **[QUICK_REFERENCE.md](./QUICK_REFERENCE.md)** — Fast lookup for common tasks and code snippets ## Core API Documentation ### Module and Service - **[api-reference/SqsModule.md](./api-reference/SqsModule.md)** — Module registration (sync and async) - **[api-reference/SqsService.md](./api-reference/SqsService.md)** — Service for sending messages and queue management - **[api-reference/Decorators.md](./api-reference/Decorators.md)** — `@SqsMessageHandler` and `@SqsConsumerEventHandler` - **[api-reference/Index.md](./api-reference/Index.md)** — API reference overview and imports ### Reference Documentation - **[types.md](./types.md)** — All exported types, interfaces, and type aliases - **[configuration.md](./configuration.md)** — Detailed configuration reference for consumers and producers - **[errors.md](./errors.md)** — Error types, conditions, and handling patterns ## Architecture and Design - **[ARCHITECTURE.md](./ARCHITECTURE.md)** — Internal architecture, initialization sequence, data flow, and design patterns ## Organization ``` /workspace/home/output/ ├── README.md # Main entry point ├── INDEX.md # This file ├── QUICK_REFERENCE.md # Fast lookup guide ├── ARCHITECTURE.md # Design and internals ├── types.md # Type definitions ├── configuration.md # Configuration reference ├── errors.md # Error handling └── api-reference/ ├── Index.md # API overview ├── SqsModule.md # Module registration ├── SqsService.md # Main service └── Decorators.md # Handler decorators ``` ## By Topic ### Getting Started 1. [README.md](./README.md) — Overview and complete example 2. [api-reference/Index.md](./api-reference/Index.md) — API overview 3. [QUICK_REFERENCE.md](./QUICK_REFERENCE.md) — Common patterns ### Module Setup - [api-reference/SqsModule.md](./api-reference/SqsModule.md) — How to register - [configuration.md](./configuration.md) — Configuration options ### Using the Service - [api-reference/SqsService.md](./api-reference/SqsService.md) — Available methods - [QUICK_REFERENCE.md](./QUICK_REFERENCE.md#sending-messages) — Code examples ### Message Handling - [api-reference/Decorators.md](./api-reference/Decorators.md) — Handler decorators - [README.md](./README.md#complete-example) — Full example - [ARCHITECTURE.md](./ARCHITECTURE.md#message-processing-flow) — How it works ### Error Handling - [errors.md](./errors.md) — Error types and patterns - [api-reference/Decorators.md](./api-reference/Decorators.md#sqsconsumereventhandler) — Event handlers - [QUICK_REFERENCE.md](./QUICK_REFERENCE.md#error-handling) — Quick examples ### Configuration - [configuration.md](./configuration.md) — Full options reference - [types.md](./types.md#sqsoptions) — Type definitions - [QUICK_REFERENCE.md](./QUICK_REFERENCE.md#configuration-options) — Quick reference ### Understanding the Code - [ARCHITECTURE.md](./ARCHITECTURE.md) — How it works internally - [types.md](./types.md) — All types and interfaces - [api-reference/Index.md](./api-reference/Index.md) — Module flow ## By Use Case | I want to... | Start here | |---|---| | Learn about the library | [README.md](./README.md) | | Set up the module | [api-reference/SqsModule.md](./api-reference/SqsModule.md) | | Send messages | [api-reference/SqsService.md](./api-reference/SqsService.md#send) | | Handle incoming messages | [api-reference/Decorators.md](./api-reference/Decorators.md) | | Handle errors | [errors.md](./errors.md) | | Configure consumers/producers | [configuration.md](./configuration.md) | | Use async config | [api-reference/SqsModule.md](./api-reference/SqsModule.md#registerasync) | | Find a quick example | [QUICK_REFERENCE.md](./QUICK_REFERENCE.md) | | Understand the architecture | [ARCHITECTURE.md](./ARCHITECTURE.md) | | Look up a type | [types.md](./types.md) | | Debug an error | [errors.md](./errors.md) | ## File Statistics | File | Lines | Purpose | |------|-------|---------| | README.md | 422 | Project overview and features | | QUICK_REFERENCE.md | 381 | Fast lookup guide | | ARCHITECTURE.md | 448 | Design and internals | | configuration.md | 428 | Configuration reference | | errors.md | 427 | Error handling | | types.md | 373 | Type definitions | | api-reference/SqsModule.md | 177 | Module registration | | api-reference/SqsService.md | 314 | Service methods | | api-reference/Decorators.md | 228 | Handler decorators | | api-reference/Index.md | 256 | API overview | | **Total** | **3,632** | **Complete reference** | ``` -------------------------------- ### Purging or Getting Attributes for Non-existent Queue Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/errors.md This error occurs when attempting to purge a queue or get its attributes using a name that is not registered as either a consumer or producer. Ensure the queue name is registered. ```typescript try { await sqsService.purgeQueue('missing-queue'); } catch (error) { console.error(error.message); // "Consumer/Producer does not exist: missing-queue" } ``` -------------------------------- ### Configure SQS Client Options Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/Index.md Demonstrates two methods for configuring SQS clients: letting the library create clients by providing a region, or providing explicit SQSClient instances for custom configurations. ```typescript // Option 1: Let library create clients { name: 'queue', queueUrl: '...', region: 'us-east-1', } ``` ```typescript // Option 2: Provide explicit client import { SQSClient } from '@aws-sdk/client-sqs'; const client = new SQSClient({ region: 'us-east-1', credentials: { ... }, }); { name: 'queue', queueUrl: '...', sqs: client, } ``` -------------------------------- ### Get Queue Attributes Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Retrieve attributes for a specified queue, such as the `ApproximateNumberOfMessages`, using the `SqsService.getQueueAttributes` method. ```typescript const attrs = await this.sqs.getQueueAttributes('queue-name'); console.log(attrs.ApproximateNumberOfMessages); ``` -------------------------------- ### SqsOptions Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/types.md Root configuration object passed to `SqsModule.register()` or returned by factory in `SqsModule.registerAsync()`. It defines arrays of consumer and producer configurations, an optional logger, and global stop options. ```APIDOC ## SqsOptions ### Description Root configuration object passed to `SqsModule.register()` or returned by factory in `SqsModule.registerAsync()`. It defines arrays of consumer and producer configurations, an optional logger, and global stop options. ### Type Definition ```typescript interface SqsOptions { consumers?: SqsConsumerOptions[]; producers?: SqsProducerOptions[]; logger?: LoggerService; globalStopOptions?: StopOptions; } ``` ### Fields #### consumers - **consumers** (SqsConsumerOptions[]) - Optional - Array of consumer configurations for SQS queue polling #### producers - **producers** (SqsProducerOptions[]) - Optional - Array of producer configurations for sending messages #### logger - **logger** (LoggerService) - Optional - Custom NestJS logger instance; defaults to NestJS Logger #### globalStopOptions - **globalStopOptions** (StopOptions) - Optional - Default stop options applied to all consumers if their own stopOptions not specified ``` -------------------------------- ### Get Producer Queue Size Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Check the current number of messages queued for sending by a specific producer using `SqsService.getProducerQueueSize`. ```typescript const size = this.sqs.getProducerQueueSize('producer-name'); ``` -------------------------------- ### Minimal Region-Based Consumer Configuration Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Configure consumers with minimal settings by providing only the region; the library will create the SQSClient. ```typescript SqsModule.register({ consumers: [ { name: 'my-queue', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/my-queue', region: 'us-east-1', // Library creates SQSClient }, ], }) ``` -------------------------------- ### Catching Module Initialization Errors Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Use a try-catch block during application startup to handle potential errors during SQS module initialization, such as detecting duplicate consumer or producer configurations. ```typescript try { // During app startup } catch (error: unknown) { if (error instanceof Error && error.message.includes('already exists')) { console.error('Duplicate consumer/producer configuration'); } } ``` -------------------------------- ### Injecting SqsService in Providers Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Demonstrates how `SqsService` can be injected into any provider after `SqsModule` is registered globally. ```typescript // In any provider constructor(private sqsService: SqsService) {} ``` -------------------------------- ### Get Producer Queue Size Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsService.md Returns the number of messages in the producer's internal queue buffer before sending to AWS SQS. Useful for monitoring producer batch processing. ```typescript async checkProducerStatus() { const queueSize = this.sqsService.getProducerQueueSize('myProducer'); if (queueSize > 100) { console.warn('Producer queue is backed up with 100+ messages'); } } ``` -------------------------------- ### Import Core and Type Definitions Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Import the main module, service, and handler decorators, along with necessary type definitions for SQS options and AWS messages. ```typescript // Main imports import { SqsModule, SqsService, SqsMessageHandler, SqsConsumerEventHandler } from '@ssut/nestjs-sqs'; // Type imports import type { SqsOptions, Message, SqsConsumerOptions, SqsProducerOptions } from '@ssut/nestjs-sqs'; // AWS types import { Message } from '@aws-sdk/client-sqs'; ``` -------------------------------- ### Get SQS Queue Attributes Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsService.md Retrieves all attributes of an SQS queue, such as visibility timeout, message retention period, and message count. Useful for monitoring queue configuration and status. ```typescript async monitorQueue() { const attrs = await this.sqsService.getQueueAttributes('myQueue'); console.log(`Queue has ${attrs.ApproximateNumberOfMessages} messages`); console.log(`Queue ARN: ${attrs.QueueArn}`); console.log(`Is FIFO: ${attrs.FifoQueue === 'true'}`); } ``` -------------------------------- ### Configure SQS with LocalStack Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Sets up the SQS module to use a local SQS instance running on LocalStack. This is useful for local development and integration testing. ```typescript const sqs = new SQSClient({ endpoint: 'http://localhost:4566', credentials: { accessKeyId: 'test', secretAccessKey: 'test' }, }); SqsModule.register({ consumers: [{ name: 'test', queueUrl: 'http://localhost:4566/000000000000/test-queue', sqs, }], }); ``` -------------------------------- ### Synchronous SQS Module Registration Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsModule.md Use the `register` method for synchronous configuration of SQS consumers and producers when all settings are known at application startup. This method sets up the SqsModule globally and provides the SqsService. ```typescript import { Module } from '@nestjs/common'; import { SqsModule } from '@ssut/nestjs-sqs'; @Module({ imports: [ SqsModule.register({ consumers: [ { name: 'myConsumer', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/my-queue', region: 'us-east-1', batchSize: 10, waitTimeSeconds: 20, }, ], producers: [ { name: 'myProducer', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/my-queue', region: 'us-east-1', }, ], }), ], }) export class AppModule {} ``` -------------------------------- ### registerAsync Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsModule.md Asynchronously registers the SqsModule with configuration resolved at runtime via factory, class, or existing service. This method allows deferring module configuration until runtime, which is useful when configuration depends on environment variables, external services, or other injectable providers. ```APIDOC ## registerAsync ### Description Asynchronously registers the SqsModule with configuration resolved at runtime via factory, class, or existing service. ### Method Signature ```typescript static registerAsync(options: SqsModuleAsyncOptions): DynamicModule ``` ### Parameters #### options - **options** (SqsModuleAsyncOptions) - Required - Async configuration with useFactory, useClass, or useExisting ### Return Type `DynamicModule` — A NestJS dynamic module with asynchronously resolved configuration ### Supported Patterns 1. **useFactory** — Provide a function that returns `SqsOptions` (sync or async) 2. **useClass** — Provide a class implementing `SqsModuleOptionsFactory` interface 3. **useExisting** — Provide an existing service instance that implements `SqsModuleOptionsFactory` ### Throws Same errors as `register` method regarding duplicate consumer/producer names. ### Example — Using Factory ```typescript import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { SqsModule } from '@ssut/nestjs-sqs'; @Module({ imports: [ ConfigModule.forRoot(), SqsModule.registerAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => { return { consumers: [ { name: 'myConsumer', queueUrl: configService.get('SQS_QUEUE_URL'), region: configService.get('AWS_REGION'), }, ], producers: [ { name: 'myProducer', queueUrl: configService.get('SQS_QUEUE_URL'), region: configService.get('AWS_REGION'), }, ], }; }, inject: [ConfigService], }), ], }) export class AppModule {} ``` ### Example — Using Class ```typescript import { Injectable } from '@nestjs/common'; import { SqsModuleOptionsFactory } from '@ssut/nestjs-sqs'; @Injectable() export class SqsConfigService implements SqsModuleOptionsFactory { async createOptions() { return { consumers: [ { name: 'myConsumer', queueUrl: process.env.SQS_QUEUE_URL, region: process.env.AWS_REGION, }, ], producers: [ { name: 'myProducer', queueUrl: process.env.SQS_QUEUE_URL, region: process.env.AWS_REGION, }, ], }; } } @Module({ imports: [ SqsModule.registerAsync({ useClass: SqsConfigService, }), ], }) export class AppModule {} ``` ``` -------------------------------- ### Dependency Graph Overview Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Illustrates the dependency relationships within the NestJS SQS module, including `SqsService`, `DiscoveryService`, and configuration tokens. ```plaintext Application Providers ↓ SqsService (Injectable) ├─ Injected as dependency │ ├─ depends on: SQS_OPTIONS (DI token) │ └─ provided by: SqsModule.register() | registerAsync() │ ├─ depends on: DiscoveryService │ └─ provided by: DiscoveryModule (imported by SqsModule) │ └─ Internal state: ├─ consumers: Map ├─ producers: Map └─ options: SqsOptions DiscoveryModule └─ provides: DiscoveryService └─ used for: Finding decorated methods at runtime ``` -------------------------------- ### Async Configuration with useFactory and ConfigService Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Configure SQS consumers and producers dynamically using `useFactory` and NestJS `ConfigService`. This approach allows reading configuration from environment variables. ```typescript // .env SQS_QUEUE_URL=https://sqs.us-east-1.amazonaws.com/123456789012/my-queue AWS_REGION=us-east-1 AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... SQS_BATCH_SIZE=10 // app.module.ts SqsModule.registerAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ consumers: [ { name: 'default', queueUrl: configService.getOrThrow('SQS_QUEUE_URL'), region: configService.get('AWS_REGION'), batchSize: configService.get('SQS_BATCH_SIZE', { infer: true }), }, ], }), inject: [ConfigService], }) ``` -------------------------------- ### Handler Discovery Flow Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Explains how the library discovers and wires up message handler methods decorated with `@SqsMessageHandler` to SQS consumer instances. ```mermaid @SqsMessageHandler('queue-name') ↓ SetMetadata(SQS_CONSUMER_METHOD, { name, batch }) ↓ DiscoveryService discovers metadata ↓ Wire handler to Consumer instance ↓ Consumer calls handler on message receipt ``` -------------------------------- ### Async Registration with Class Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Register SQS module asynchronously using an existing class. The module will instantiate this class and call its `createOptions` method. ```typescript SqsModule.registerAsync({ useClass: SqsConfigService }) ↓ Create instance of SqsConfigService ↓ Call createOptions() method ↓ Inject returned options into SqsService ``` -------------------------------- ### Register SQS Module with Basic Configuration Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Register the SQS module with basic configuration for consumers and producers, specifying queue URLs and regions. ```typescript SqsModule.register({ consumers: [ { name: 'queue-name', queueUrl: 'https://sqs.REGION.amazonaws.com/ACCOUNT/QUEUE', region: 'us-east-1', } ], producers: [ { name: 'queue-name', queueUrl: 'https://sqs.REGION.amazonaws.com/ACCOUNT/QUEUE', region: 'us-east-1', } ], }) ``` -------------------------------- ### Mock SqsService for Testing Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Provides a mock implementation of SqsService for unit testing. Use this when you need to test services that depend on SqsService without actual SQS interaction. ```typescript const mockSqs = { send: jest.fn(), purgeQueue: jest.fn(), getQueueAttributes: jest.fn(), consumers: new Map(), producers: new Map(), }; Test.createTestingModule({ providers: [ MyService, { provide: SqsService, useValue: mockSqs }, ], }).compile(); ``` -------------------------------- ### SqsOptions Interface Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/types.md Root configuration object for the SQS module. Use this to configure consumers, producers, and global settings. ```typescript interface SqsOptions { consumers?: SqsConsumerOptions[]; producers?: SqsProducerOptions[]; logger?: LoggerService; globalStopOptions?: StopOptions; } ``` -------------------------------- ### Configure Dead Letter Queue (DLQ) Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Sets up a main queue and a dead-letter queue (DLQ) for handling processing failures. Failed messages from the main queue can be sent to the DLQ for later inspection or reprocessing. ```typescript SqsModule.register({ consumers: [ { name: 'main', queueUrl: '...' }, { name: 'dlq', queueUrl: '...' }, ], producers: [ { name: 'dlq', queueUrl: '...' }, ], }) @SqsConsumerEventHandler('main', 'processing_error') async handleFailure(error: Error, message: Message) { if (shouldGoToDLQ()) { await this.sqs.send('dlq', { id: message.MessageId, body: JSON.parse(message.Body), }); } } ``` -------------------------------- ### Async Registration with Existing Service Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Register SQS module asynchronously using an existing service. The module finds the service in the DI container and calls its `createOptions` method. ```typescript SqsModule.registerAsync({ useExisting: ExistingService }) ↓ Locate ExistingService in DI container ↓ Call its createOptions() method ↓ Inject returned options into SqsService ``` -------------------------------- ### Module Registration Phase Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Outlines the steps involved in registering the SQS module within a NestJS application. ```mermaid 1. User calls SqsModule.register(options) or registerAsync(options) ↓ 2. Module returns DynamicModule with providers ↓ 3. NestJS DI container registers providers ↓ 4. SqsService is instantiated with options ``` -------------------------------- ### Async Configuration with Factory Function Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Resolve SQS module configuration at runtime using a factory function, allowing dynamic retrieval of settings like queue URLs and regions. ```typescript SqsModule.registerAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ consumers: [ { name: 'my-queue', queueUrl: configService.get('SQS_QUEUE_URL'), region: configService.get('AWS_REGION'), batchSize: configService.get('SQS_BATCH_SIZE', 10), }, ], producers: [ { name: 'my-queue', queueUrl: configService.get('SQS_QUEUE_URL'), region: configService.get('AWS_REGION'), }, ], }), inject: [ConfigService], }) ``` -------------------------------- ### SqsModule.register Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsModule.md Synchronously registers the SqsModule with consumer and producer configurations. This method is suitable when configuration is known at application startup. ```APIDOC ## SqsModule.register ### Description Synchronously registers the SqsModule with consumer and producer configurations. This method is suitable when configuration is known at application startup and does not depend on external services or environment resolution. ### Method `static register(options: SqsOptions): DynamicModule` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | options | [SqsOptions](#sqsoptions) | Yes | Module configuration including consumers and producers arrays | ### Return Type `DynamicModule` — A NestJS dynamic module with configured providers and exports ### Throws | Error | Condition | |-------|-----------| | `Error: Consumer already exists: {name}` | A consumer with the same name is registered twice | | `Error: Producer already exists: {name}` | A producer with the same name is registered twice | ### Example ```typescript import { Module } from '@nestjs/common'; import { SqsModule } from '@ssut/nestjs-sqs'; @Module({ imports: [ SqsModule.register({ consumers: [ { name: 'myConsumer', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/my-queue', region: 'us-east-1', batchSize: 10, waitTimeSeconds: 20, }, ], producers: [ { name: 'myProducer', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/my-queue', region: 'us-east-1', }, ], }), ], }) export class AppModule {} ``` ``` -------------------------------- ### Import Core Components Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/Index.md Import the main components of the library from the root package. These include the module, service, and message handler decorators. ```typescript import { SqsModule, SqsService, SqsMessageHandler, SqsConsumerEventHandler, } from '@ssut/nestjs-sqs'; ``` -------------------------------- ### Injecting SqsService Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsService.md Demonstrates how to inject the SqsService into a NestJS provider using constructor injection. This service is globally available after SqsModule registration. ```typescript import { Injectable } from '@nestjs/common'; import { SqsService } from '@ssut/nestjs-sqs'; @Injectable() export class OrderService { constructor(private sqsService: SqsService) {} // ... methods using sqsService } ``` -------------------------------- ### FIFO Queue Consumer and Producer Configuration Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Demonstrates that consumer configuration for FIFO queues is standard, while message sending requires FIFO-specific parameters like groupId and deduplicationId. ```typescript // Consumer config remains the same { name: 'fifo-queue', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/orders.fifo', } // Message sending includes groupId and deduplicationId await sqsService.send('fifo-queue', { id: 'msg-001', body: { orderId: 'ORD-123' }, groupId: 'group-a', // FIFO: required deduplicationId: 'msg-001', // FIFO: required for content dedup disabled }) ``` -------------------------------- ### Event Listener Architecture Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Shows how event listeners are registered with a `Consumer` and how different events trigger specific handler signatures. ```typescript Consumer.addListener(eventName, handler) ↓ When event emitted: ├─ processing_error → (error, message) ├─ error → (error) ├─ timeout_error → (error) ├─ empty → () └─ ...other events → varies ``` -------------------------------- ### Asynchronous Module Registration with ConfigModule Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/Index.md Register the SqsModule asynchronously using `registerAsync` and integrate with `@nestjs/config` to load SQS configuration from environment variables. This is the recommended pattern for managing configuration. ```typescript // Recommended pattern for environment-based configuration SqsModule.registerAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ consumers: [{ name: 'default', queueUrl: configService.getOrThrow('SQS_QUEUE_URL'), region: configService.get('AWS_REGION'), }], producers: [{ name: 'default', queueUrl: configService.getOrThrow('SQS_QUEUE_URL'), region: configService.get('AWS_REGION'), }], }), inject: [ConfigService], }) ``` -------------------------------- ### Register SQS Module Asynchronously with Existing Source: https://github.com/ssut/nestjs-sqs/blob/master/README.md Use registerAsync with an existing configuration service instance. ```typescript SqsModule.registerAsync({ imports: [ConfigModule], useExisting: ConfigService, }); ``` -------------------------------- ### Register SQS Module Async with Class Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsModule.md Use registerAsync with a class that implements SqsModuleOptionsFactory to provide SQS module configuration asynchronously. The class's createOptions method resolves configuration, such as queue URLs and regions, from environment variables. ```typescript import { Injectable } from '@nestjs/common'; import { SqsModuleOptionsFactory } from '@ssut/nestjs-sqs'; @Injectable() export class SqsConfigService implements SqsModuleOptionsFactory { async createOptions() { return { consumers: [ { name: 'myConsumer', queueUrl: process.env.SQS_QUEUE_URL, region: process.env.AWS_REGION, }, ], producers: [ { name: 'myProducer', queueUrl: process.env.SQS_QUEUE_URL, region: process.env.AWS_REGION, }, ], }; } } @Module({ imports: [ SqsModule.registerAsync({ useClass: SqsConfigService, }), ], }) export class AppModule {} ``` -------------------------------- ### Async Registration with Factory Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Register SQS module asynchronously using a factory function. Dependencies for the factory are injected via `inject`. ```typescript SqsModule.registerAsync({ useFactory: (configService) => ({ ... }), inject: [ConfigService] }) ↓ Create provider with useFactory ↓ Resolve injected dependencies ↓ Call factory to get options ↓ Inject resolved options into SqsService ``` -------------------------------- ### Synchronous Module Registration Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/Index.md Register the SqsModule synchronously by providing an options object. This sets up consumers and producers with their respective configurations. ```typescript // app.module.ts import { SqsModule } from '@ssut/nestjs-sqs'; @Module({ imports: [ SqsModule.register({ consumers: [ { name: 'order-queue', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/orders', region: 'us-east-1', }, ], producers: [ { name: 'order-queue', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/orders', region: 'us-east-1', }, ], }), ], }) export class AppModule {} ``` -------------------------------- ### Register SQS Module Asynchronously with Class Source: https://github.com/ssut/nestjs-sqs/blob/master/README.md Use registerAsync with a configuration service class to provide module options. ```typescript SqsModule.registerAsync({ useClass: SqsConfigService, }); ``` -------------------------------- ### SQS Consumer Configuration Options Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Configure consumer behavior including batch size, polling duration, visibility timeout, message attributes, and graceful shutdown options. ```typescript { name: 'queue-name', queueUrl: 'https://...', region: 'us-east-1', batchSize: 10, waitTimeSeconds: 20, visibilityTimeout: 60, messageAttributeNames: ['All'], terminateVisibilityTimeout: true, stopOptions: { emitStopEvent: true }, } ``` -------------------------------- ### SQS Producer Configuration Options Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/QUICK_REFERENCE.md Configure producer behavior including batch size for sending messages and delay for partial batches. ```typescript { name: 'queue-name', queueUrl: 'https://...', region: 'us-east-1', batchSize: 10, batchDelayMs: 100, } ``` -------------------------------- ### Reusing an Existing SqsModuleOptionsFactory Service Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Use `useExisting` to reference an already defined service that implements `SqsModuleOptionsFactory`. This is useful for sharing configuration logic across modules. ```typescript @Module({ imports: [ ConfigModule, SqsModule.registerAsync({ useExisting: SqsConfigService, }), ], providers: [SqsConfigService], }) export class AppModule {} ``` -------------------------------- ### SqsModuleOptionsFactory Interface Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/types.md Interface for creating custom SqsOptions providers. Implement this to define your module's configuration. ```typescript interface SqsModuleOptionsFactory { createOptions(): Promise | SqsOptions; } ``` -------------------------------- ### Graceful Shutdown Configuration for Consumers Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Configure graceful consumer shutdown using `stopOptions` at the consumer level or `globalStopOptions` at the module level. The `emitStopEvent` option controls whether a 'stopped' event is emitted before shutdown. ```typescript SqsModule.register({ consumers: [ { name: 'my-queue', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/my-queue', // Consumer-specific stop options (takes precedence) stopOptions: { emitStopEvent: true, }, }, ], // Applied to all consumers without explicit stopOptions globalStopOptions: { emitStopEvent: true, }, }) ``` -------------------------------- ### SqsModuleAsyncOptions Interface Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/types.md Defines the configuration structure for asynchronously registering the SqsModule. Requires one of useFactory, useClass, or useExisting. ```typescript interface SqsModuleAsyncOptions extends Pick { useExisting?: Type; useClass?: Type; useFactory?: (...args: any[]) => Promise | SqsOptions; inject?: any[]; } ``` -------------------------------- ### Configure Consumer with Explicit SQSClient Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/configuration.md Use an explicit SQSClient instance for advanced control over AWS credentials and SDK options when configuring consumers. ```typescript import { SQSClient } from '@aws-sdk/client-sqs'; const sqs = new SQSClient({ region: 'us-east-1', credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }, // Other SDK options }); SqsModule.register({ consumers: [ { name: 'my-queue', queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789012/my-queue', sqs, // Use explicit client }, ], }) ``` -------------------------------- ### Sending Batch Messages with SqsService Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/api-reference/SqsService.md Illustrates sending multiple messages in a single batch to an SQS queue using the `send` method. Messages are mapped to the required format, including unique IDs and FIFO parameters. ```typescript async publishNotifications(userIds: string[]) { const messages = userIds.map((userId, index) => ({ id: `${userId}-${Date.now()}-${index}`, body: { userId, event: 'notification', message: 'Hello from batch', }, groupId: 'notifications', deduplicationId: `${userId}-${Date.now()}-${index}`, })); await this.sqsService.send('notification-queue', messages); } ``` -------------------------------- ### Register SQS Module Asynchronously with Factory Source: https://github.com/ssut/nestjs-sqs/blob/master/README.md Use registerAsync with a factory function to provide module options dynamically. ```typescript SqsModule.registerAsync({ useFactory: () => { return { consumers: [...], producers: [...], }; }, }); ``` -------------------------------- ### SQS Consumer Flow Source: https://github.com/ssut/nestjs-sqs/blob/master/_autodocs/ARCHITECTURE.md Illustrates the lifecycle of a message from an SQS queue through the library's consumer to handler execution and final deletion or requeuing. ```mermaid SQS Queue ↓ Consumer.create() [sqs-consumer] ↓ @SqsMessageHandler decorated method ↓ Handler execution ↓ Message deletion / requeue on error ```