@ethberry/nestjs-sqs

中文文档
8.0.0发布于 2026/11/12MITTypeScriptES Module近 30 天下载 3555

Tested with AWS SQS, ElasticMQ, and LocalStack (see integration tests in this repo).

原始使用文档
文档目录11 节
  1. Compared to Redis and RabbitMQ transports
  2. Requirements
  3. Installation
  4. Local integration tests
  5. Quick Start
  6. Register custom transport
  7. Decorate methods
  8. Handler context ( SqsContext )
  9. Graceful shutdown
  10. Produce messages
  11. License

NestJS SQS

Tested with AWS SQS, ElasticMQ, and LocalStack (see integration tests in this repo).

NestJS SQS is a project to make SQS easier to use and control some required flows with NestJS. This module provides decorator-based message handling suited for simple use.

This library internally relies on bbc/sqs-producer and bbc/sqs-consumer, and implements some more useful features on top of the basic functionality given by them.

The default SqsSerializer and SqsDeserializer work for standard queues. Message bodies are the same JSON for FIFO; FIFO metadata is on the SQS message, not in Body, so only the serializer changes for FIFO: register SqsFifoSerializer via the serializer option on SqsClient / SqsServer when needed (all are exported from this package).

Compared to Redis and RabbitMQ transports

Nest’s Redis and RMQ servers are first-party: multiplexed connections, push-style delivery, and rich metadata on the broker record. SQS is different by design:

TopicRedis / RMQ (typical)This SQS transport
DeliveryOften push / subscriptionLong polling (sqs-consumer)
SemanticsDepends on brokerAt-least-once; duplicates possible
Request–replyChannels / reply-toTwo queues + correlation id in the JSON body
OrderingBroker-specificStandard = best-effort; FIFO = per message group (see AWS docs)
MetadataHeaders / propertiesBody holds the Nest packet by default; use SqsContext for raw Message (attributes, receipt handle, etc.)

The Nest API stays familiar: @MessagePattern / @EventPattern, ClientProxy, and serializers—but operational behavior follows SQS (visibility timeout, DLQ, throttling). Plan retries and idempotency accordingly.

Requirements

  • Node.js 24+ (will run on 22, but not tested)

Installation

$ npm i --save @ethberry/nestjs-sqs

Local integration tests

Integration specs read ELASTICMQ_URL and LOCALSTACK_URL from a .env file at the repo root (committed defaults). Start ElasticMQ and LocalStack, then run tests:

$ npm i
$ npm run docker:sqs:up
$ npm test
$ npm run docker:sqs:down

Override endpoints by editing .env (for example different ports).

To match CI (lint + tests) after dependencies and Docker are up:

$ npm run lint && npm test

Quick Start

Register custom transport

Just like you register any other microservice

import { SQSClient } from "@aws-sdk/client-sqs";
import { SqsServer } from "@ethberry/nestjs-sqs";

const sqs = new SQSClient({
  endpoint: "http://localhost:9324",
  region: "none",
  credentials: {
    accessKeyId: "x",
    secretAccessKey: "x",
  },
});

app.connectMicroservice({
  strategy: new SqsServer({
    consumerOptions: {
      sqs,
      queueUrl: "http://localhost:9324/queue/producer",
    },
    producerOptions: {
      sqs,
      queueUrl: "http://localhost:9324/queue/consumer",
    },
  }),
});

Decorate methods

You need to decorate methods in your NestJS controller in order to have them be automatically attached as event handlers for incoming SQS messages:

@Controller()
export class SqsController {
  @MessagePattern(MESSAGE_TYPE)
  public handleMessage(message: any): Promise<any> {
    // do something, return result
  }

  @EventPattern(EVENT_TYPE)
  public handleEvent(event: any): Promise<void> {
    // do something
  }
}

Handler context (SqsContext)

Like RmqContext or RedisContext, you can inject SqsContext with @Ctx() to read the raw AWS Message, the consumer queue URL, and the pattern string. The first argument remains the deserialized payload (data from the body).

import { Controller } from "@nestjs/common";
import { Ctx, MessagePattern, Payload } from "@nestjs/microservices";
import { SqsContext } from "@ethberry/nestjs-sqs";

@Controller()
export class SqsController {
  @MessagePattern(MESSAGE_TYPE)
  public handleRpc(@Payload() data: unknown, @Ctx() ctx: SqsContext): Promise<unknown> {
    const sqs = ctx.getMessage();
    const attrs = sqs.MessageAttributes;
    // ...
    return { ok: true };
  }
}

Events emitted without a top-level id in the packet are routed with @EventPattern (same idea as other Nest transports).

Graceful shutdown

sqs-consumer can wait for the last poll and in-flight handleMessage work before stopping. Set pollingCompleteWaitTimeMs on consumerOptions (milliseconds you are willing to wait). SqsServer.close() forwards optional StopOptions to consumer.stop() (for example { abort: true } to cancel in-flight polls—use sparingly).

new SqsServer({
  consumerOptions: {
    sqs,
    queueUrl: "...",
    pollingCompleteWaitTimeMs: 10_000,
  },
  producerOptions: { sqs, queueUrl: "..." },
});

When the app stops, call app.close() (or otherwise invoke the microservice close) so the consumer shuts down.

Produce messages

import { SQSClient } from "@aws-sdk/client-sqs";
import { SqsClient, SQS_SERVICE } from "@ethberry/nestjs-sqs";

const sqs = new SQSClient({
  endpoint: "http://localhost:9324",
  region: "none",
  credentials: {
    accessKeyId: "x",
    secretAccessKey: "x",
  },
});

@Module({
  imports: [
    ClientsModule.register([
      {
        name: SQS_SERVICE,
        customClass: SqsClient,
        options: {
          consumerUrl: "http://localhost:9324/queue/consumer",
          producerUrl: "http://localhost:9324/queue/producer",
          sqs,
        },
      },
    ]),
  ],
  providers: [AppService],
})
class AppModule {}

export class AppService {
  constructor(
    @Inject(SQS_SERVICE)
    private readonly sqsClientProxy: ClientProxy,
  ) {}

  public dispatch(): Promise<void> {
    void this.sqsClientProxy.emit(EVENT_NAME, {});
  }
}

License

This project is licensed under the terms of the MIT license.

版本与发布记录

@ethberry/nestjs-sqs 共发布 8 个版本,首次发布于 2024/09/26;过去 12 个月发布了 4 个版本。

版本发布日期距今
8.0.0latest2026/11/122 天前
7.0.22026/11/112 天前
7.0.12026/11/112 天前
7.0.02026/03/227 个月前
6.0.22025/06/191.4 年前
6.0.12025/03/301.6 年前

关于 @ethberry/nestjs-sqs 的常见问题

@ethberry/nestjs-sqs 是什么?

Tested with AWS SQS, ElasticMQ, and LocalStack (see integration tests in this repo).

如何安装 @ethberry/nestjs-sqs?

在项目目录运行 npm install @ethberry/nestjs-sqs,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:rxjs(^7.0.0)、@nestjs/core(^11.0.0 || ^12.0.0)、@nestjs/common(^11.0.0 || ^12.0.0)、@nestjs/microservices(^11.0.0 || ^12.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ethberry/nestjs-sqs 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ethberry/nestjs-sqs 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@ethberry/nestjs-sqs 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@ethberry/nestjs-sqs 可以商用吗?

@ethberry/nestjs-sqs 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@ethberry/nestjs-sqs 的下载量有多少?

根据 npm 官方下载统计,@ethberry/nestjs-sqs 在 2026/10/14 – 2026/11/12 这 30 天内被下载 3,555 次,日均约 119 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ethberry/nestjs-sqs 还在维护吗?

最新版本 8.0.0 发布于 2026/11/12(2 天前);至今共发布 8 个版本,其中过去 12 个月发布了 4 个;首次发布于 2024/09/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。