sqs-consumer

  • Version 12.0.0
  • Published
  • 150 kB
  • 2 dependencies
  • Apache-2.0 license

Install

npm i sqs-consumer
yarn add sqs-consumer
pnpm add sqs-consumer

Overview

Build SQS-based Node applications without the boilerplate

Index

Classes

class Consumer

class Consumer extends TypedEventEmitter {}
  • [Usage](https://bbc.github.io/sqs-consumer/index.html#usage)

constructor

constructor(options: ConsumerOptions);

    property abortController

    abortController: AbortController;

      property queueUrl

      protected queueUrl: string;

        property status

        readonly status: { isRunning: boolean; isPolling: boolean };
        • Returns the current status of the consumer. This includes whether it is running or currently polling.

        method create

        static create: (options: ConsumerOptions) => Consumer;
        • Creates a new SQS consumer.

        method start

        start: () => void;
        • Start polling the queue for messages.

        method stop

        stop: (options?: StopOptions) => void;
        • Stop polling the queue for messages (pre existing requests will still be made until concluded).

        method updateOption

        updateOption: (
        option: UpdatableOptions,
        value: ConsumerOptions[UpdatableOptions]
        ) => void;
        • Validates and then updates the provided option to the provided value.

          Parameter option

          The option to validate and then update

          Parameter value

          The value to set the provided option to

        class SQSError

        class SQSError extends Error {}

          constructor

          constructor(message: string);

            property code

            code: string;

              property fault

              fault: 'client' | 'server';

                property messageIds

                messageIds?: string[];

                  property metadata

                  metadata?: {
                  readonly httpStatusCode?: number;
                  readonly requestId?: string;
                  readonly extendedRequestId?: string;
                  readonly cfId?: string;
                  readonly attempts?: number;
                  readonly totalRetryDelay?: number;
                  };

                    property queueUrl

                    queueUrl?: string;

                      property response

                      response?: { statusCode?: number; headers: Record<string, string>; body?: any };

                        property retryable

                        retryable: boolean;

                          property service

                          service: string;

                            property statusCode

                            statusCode: number;

                              property time

                              time: Date;

                                class StandardError

                                class StandardError extends Error {}

                                  constructor

                                  constructor(message?: string);

                                    property cause

                                    cause: Error;

                                      property messageIds

                                      messageIds: string[];

                                        property time

                                        time: Date;

                                          class TimeoutError

                                          class TimeoutError extends Error {}

                                            constructor

                                            constructor(message?: string);

                                              property cause

                                              cause: Error;

                                                property messageIds

                                                messageIds: string[];

                                                  property time

                                                  time: Date;

                                                    Interfaces

                                                    interface ConsumerOptions

                                                    interface ConsumerOptions {}
                                                    • The options for the consumer.

                                                    property alwaysAcknowledge

                                                    alwaysAcknowledge?: boolean;
                                                    • By default, the consumer will treat an empty object or array from either of the handlers as a acknowledgement of no messages and will not delete those messages as a result. Set this to true to always acknowledge all messages no matter the returned value.

                                                    property attributeNames

                                                    attributeNames?: QueueAttributeName[];
                                                    • List of queue attributes to retrieve, see [AWS docs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sqs/Variable/QueueAttributeName/).

                                                    property authenticationErrorTimeout

                                                    authenticationErrorTimeout?: number;
                                                    • The duration (in milliseconds) to wait before retrying after an authentication error.

                                                    property batchSize

                                                    batchSize?: number;
                                                    • The number of messages to request from SQS when polling (default 1).

                                                      This cannot be higher than the [AWS limit of 10](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/quotas-messages.html).

                                                    property extendedAWSErrors

                                                    extendedAWSErrors?: boolean;
                                                    • Set this to true if you want to receive additional information about the error that occurred from AWS, such as the response and metadata.

                                                    property handleMessageTimeout

                                                    handleMessageTimeout?: number;
                                                    • Time in ms to wait for handleMessage to process a message before timing out.

                                                      Emits timeout_error on timeout. By default, if handleMessage times out, the unprocessed message returns to the end of the queue.

                                                    property heartbeatInterval

                                                    heartbeatInterval?: number;
                                                    • The interval (in seconds) between requests to extend the message visibility timeout.

                                                      On each heartbeat the visibility is extended by adding visibilityTimeout to the number of seconds since the start of the handler function.

                                                      This value must less than visibilityTimeout.

                                                    property messageAttributeNames

                                                    messageAttributeNames?: string[];
                                                    • List of message attributes to retrieve (i.e. ['name', 'address']).

                                                    property messageSystemAttributeNames

                                                    messageSystemAttributeNames?: MessageSystemAttributeName[];
                                                    • A list of attributes that need to be returned along with each message.

                                                    property pollingCompleteWaitTimeMs

                                                    pollingCompleteWaitTimeMs?: number;
                                                    • If you want the stop action to wait for the final poll to complete and in-flight messages to be processed before emitting 'stopped' set this to the max amount of time to wait.

                                                    property pollingWaitTimeMs

                                                    pollingWaitTimeMs?: number;
                                                    • The duration (in milliseconds) to wait before repolling the queue.

                                                    property queueUrl

                                                    queueUrl: string;
                                                    • The SQS queue URL.

                                                    property region

                                                    region?: string;
                                                    • The AWS region.

                                                    property shouldDeleteMessages

                                                    shouldDeleteMessages?: boolean;
                                                    • Default to true, if you don't want the package to delete messages from sqs set this to false.

                                                    property sqs

                                                    sqs?: SQSClient;
                                                    • An optional [SQS Client](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-sqs/classes/sqsclient.html) object to use if you need to configure the client manually.

                                                    property stopped

                                                    stopped?: boolean;

                                                    property suppressFifoWarning

                                                    suppressFifoWarning?: boolean;
                                                    • Set this to true if you want to suppress the warning about FIFO queues.

                                                    property terminateVisibilityTimeout

                                                    terminateVisibilityTimeout?:
                                                    | boolean
                                                    | number
                                                    | ((messages: Message[]) => number);
                                                    • If true, sets the message visibility timeout to 0 after a processing_error. You can also specify a different timeout using a number. If you would like to use exponential backoff, you can pass a function that returns a number and it will use that as the value for the timeout.

                                                    property useQueueUrlAsEndpoint

                                                    useQueueUrlAsEndpoint?: boolean;
                                                    • Set this value to false to ignore the queueUrl and use the client's resolved endpoint, which may be a custom endpoint.

                                                    property visibilityTimeout

                                                    visibilityTimeout?: number;
                                                    • The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved by a ReceiveMessage request.

                                                    property waitTimeSeconds

                                                    waitTimeSeconds?: number;
                                                    • The duration (in seconds) for which the call will wait for a message to arrive in the queue before returning.

                                                    method handleMessage

                                                    handleMessage: (message: Message) => Promise<Message | void>;
                                                    • An async function (or function that returns a Promise) to be called whenever a message is received.

                                                      In the case that you need to acknowledge the message, return an object containing the MessageId that you'd like to acknowledge.

                                                    method handleMessageBatch

                                                    handleMessageBatch: (messages: Message[]) => Promise<Message[] | void>;
                                                    • An async function (or function that returns a Promise) to be called whenever a batch of messages is received. Similar to handleMessage but will receive the list of messages, not each message individually.

                                                      **If both are set, handleMessageBatch overrides handleMessage**.

                                                      In the case that you need to ack only some of the messages, return an array with the successful messages only.

                                                    method postReceiveMessageCallback

                                                    postReceiveMessageCallback: () => Promise<void>;
                                                    • An async function (or function that returns a Promise) to be called right after the SQS Client sends a receive message command.

                                                      This function is usefull if SQS Client module exports have been modified, for example to add middlewares.

                                                    method preReceiveMessageCallback

                                                    preReceiveMessageCallback: () => Promise<void>;
                                                    • An async function (or function that returns a Promise) to be called right before the SQS Client sends a receive message command.

                                                      This function is usefull if SQS Client module exports have been modified, for example to add middlewares.

                                                    interface Events

                                                    interface Events {}
                                                    • These are the events that the consumer emits. Each event will receive QueueMetadata as the last argument, which is added automatically by the emitter.

                                                      Example 1

                                                      consumer.on('message_received', (message, metadata) => { console.log(Received message from queue: ${metadata.queueUrl}); console.log(message); });

                                                    property aborted

                                                    aborted: [];
                                                    • Fired when requests to SQS were aborted.

                                                    property empty

                                                    empty: [];
                                                    • Fired when the queue is empty (All messages have been consumed).

                                                    property error

                                                    error: [Error, Message | Message[] | undefined];
                                                    • Fired when an error occurs interacting with the queue.

                                                      If the error correlates to a message, that message is included in Params

                                                    property message_processed

                                                    message_processed: [Message];
                                                    • Fired when a message is successfully processed and removed from the queue.

                                                    property message_received

                                                    message_received: [Message];
                                                    • Fired when a message is received.

                                                    property option_updated

                                                    option_updated: [UpdatableOptions, ConsumerOptions[UpdatableOptions]];
                                                    • Fired when an option is updated

                                                    property processing_error

                                                    processing_error: [Error, Message];
                                                    • Fired when an error occurs processing the message.

                                                    property response_processed

                                                    response_processed: [];
                                                    • Fired after one batch of items (up to batchSize) has been successfully processed.

                                                    property started

                                                    started: [];
                                                    • Fired when the consumer starts its work..

                                                    property stopped

                                                    stopped: [];
                                                    • Fired when the consumer finally stops its work.

                                                    property timeout_error

                                                    timeout_error: [Error, Message];
                                                    • Fired when handleMessageTimeout is supplied as an option and if handleMessage times out.

                                                    property waiting_for_polling_to_complete

                                                    waiting_for_polling_to_complete: [];
                                                    • Fired when the Consumer is waiting for polling to complete before stopping.

                                                    property waiting_for_polling_to_complete_timeout_exceeded

                                                    waiting_for_polling_to_complete_timeout_exceeded: [];
                                                    • Fired when the Consumer has waited for polling to complete and is stopping due to a timeout.

                                                    interface QueueMetadata

                                                    interface QueueMetadata {}
                                                    • Metadata about the queue that is added to every event

                                                    property queueUrl

                                                    queueUrl?: string;

                                                      interface StopOptions

                                                      interface StopOptions {}
                                                      • The options for the stop method.

                                                      property abort

                                                      abort?: boolean;
                                                      • Default to false, if you want the stop action to also abort requests to SQS set this to true.

                                                      Type Aliases

                                                      type AWSError

                                                      type AWSError = {
                                                      /**
                                                      * Name, eg. ConditionalCheckFailedException
                                                      */
                                                      readonly name: string;
                                                      /**
                                                      * Human-readable error response message
                                                      */
                                                      message: string;
                                                      /**
                                                      * Non-standard stacktrace
                                                      */
                                                      stack?: string;
                                                      /**
                                                      * Whether the client or server are at fault.
                                                      */
                                                      readonly $fault: 'client' | 'server';
                                                      /**
                                                      * Represents an HTTP message as received in reply to a request
                                                      */
                                                      readonly $response?: {
                                                      /**
                                                      * The status code of the HTTP response.
                                                      */
                                                      statusCode?: number;
                                                      /**
                                                      * The headers of the HTTP message.
                                                      */
                                                      headers: Record<string, string>;
                                                      /**
                                                      * The body of the HTTP message.
                                                      * Can be: ArrayBuffer | ArrayBufferView | string | Uint8Array | Readable | ReadableStream
                                                      */
                                                      body?: any;
                                                      };
                                                      /**
                                                      * The service that encountered the exception.
                                                      */
                                                      readonly $service?: string;
                                                      /**
                                                      * Indicates that an error MAY be retried by the client.
                                                      */
                                                      readonly $retryable?: {
                                                      /**
                                                      * Indicates that the error is a retryable throttling error.
                                                      */
                                                      readonly throttling?: boolean;
                                                      };
                                                      readonly $metadata: {
                                                      /**
                                                      * The status code of the last HTTP response received for this operation.
                                                      */
                                                      readonly httpStatusCode?: number;
                                                      /**
                                                      * A unique identifier for the last request sent for this operation. Often
                                                      * requested by AWS service teams to aid in debugging.
                                                      */
                                                      readonly requestId?: string;
                                                      /**
                                                      * A secondary identifier for the last request sent. Used for debugging.
                                                      */
                                                      readonly extendedRequestId?: string;
                                                      /**
                                                      * A tertiary identifier for the last request sent. Used for debugging.
                                                      */
                                                      readonly cfId?: string;
                                                      /**
                                                      * The number of times this operation was attempted.
                                                      */
                                                      readonly attempts?: number;
                                                      /**
                                                      * The total amount of time (in milliseconds) that was spent waiting between
                                                      * retry attempts.
                                                      */
                                                      readonly totalRetryDelay?: number;
                                                      };
                                                      };
                                                      • The error object that is emitted with error events from AWS.

                                                      type UpdatableOptions

                                                      type UpdatableOptions =
                                                      | 'visibilityTimeout'
                                                      | 'batchSize'
                                                      | 'waitTimeSeconds'
                                                      | 'pollingWaitTimeMs';
                                                      • A subset of the ConsumerOptions that can be updated at runtime.

                                                      Package Files (4)

                                                      Dependencies (2)

                                                      Dev Dependencies (29)

                                                      Peer Dependencies (1)

                                                      Badge

                                                      To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                      You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/sqs-consumer.

                                                      • Markdown
                                                        [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/sqs-consumer)
                                                      • HTML
                                                        <a href="https://www.jsdocs.io/package/sqs-consumer"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>