Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: cleaning up code #342

Merged
merged 1 commit into from
Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 9 additions & 73 deletions src/consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,83 +18,19 @@ import {
import Debug from 'debug';
import { EventEmitter } from 'events';

import { AWSError, ConsumerOptions, Events } from './types';
import { ConsumerOptions, Events } from './types';
import { createTimeout } from './timeout';
import { autoBind } from './bind';
import { SQSError, TimeoutError } from './errors';
import {
SQSError,
TimeoutError,
toSQSError,
isConnectionError
} from './errors';
import { assertOptions, hasMessages } from './validation';

const debug = Debug('sqs-consumer');

const requiredOptions = [
'queueUrl',
// only one of handleMessage / handleMessagesBatch is required
'handleMessage|handleMessageBatch'
];

interface TimeoutResponse {
timeout: NodeJS.Timeout;
pending: Promise<void>;
}

function createTimeout(duration: number): TimeoutResponse[] {
let timeout;
const pending = new Promise((_, reject) => {
timeout = setTimeout((): void => {
reject(new TimeoutError());
}, duration);
});
return [timeout, pending];
}

function assertOptions(options: ConsumerOptions): void {
requiredOptions.forEach((option) => {
const possibilities = option.split('|');
if (!possibilities.find((p) => options[p])) {
throw new Error(
`Missing SQS consumer option [ ${possibilities.join(' or ')} ].`
);
}
});

if (options.batchSize > 10 || options.batchSize < 1) {
throw new Error('SQS batchSize option must be between 1 and 10.');
}

if (
options.heartbeatInterval &&
!(options.heartbeatInterval < options.visibilityTimeout)
) {
throw new Error('heartbeatInterval must be less than visibilityTimeout.');
}
}

function isConnectionError(err: Error): boolean {
if (err instanceof SQSError) {
return (
err.statusCode === 403 ||
err.code === 'CredentialsError' ||
err.code === 'UnknownEndpoint' ||
err.code === 'AWS.SimpleQueueService.NonExistentQueue'
);
}
return false;
}

function toSQSError(err: AWSError, message: string): SQSError {
const sqsError = new SQSError(message);
sqsError.code = err.name;
sqsError.statusCode = err.$metadata?.httpStatusCode;
sqsError.retryable = err.$retryable?.throttling;
sqsError.service = err.$service;
sqsError.fault = err.$fault;
sqsError.time = new Date();

return sqsError;
}

function hasMessages(response: ReceiveMessageCommandOutput): boolean {
return response.Messages && response.Messages.length > 0;
}

export class Consumer extends EventEmitter {
private queueUrl: string;
private handleMessage: (message: Message) => Promise<void>;
Expand Down
28 changes: 27 additions & 1 deletion src/errors.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { AWSError } from './types';

class SQSError extends Error {
code: string;
statusCode: number;
Expand All @@ -20,4 +22,28 @@ class TimeoutError extends Error {
}
}

export { SQSError, TimeoutError };
function isConnectionError(err: Error): boolean {
if (err instanceof SQSError) {
return (
err.statusCode === 403 ||
err.code === 'CredentialsError' ||
err.code === 'UnknownEndpoint' ||
err.code === 'AWS.SimpleQueueService.NonExistentQueue'
);
}
return false;
}

function toSQSError(err: AWSError, message: string): SQSError {
const sqsError = new SQSError(message);
sqsError.code = err.name;
sqsError.statusCode = err.$metadata?.httpStatusCode;
sqsError.retryable = err.$retryable?.throttling;
sqsError.service = err.$service;
sqsError.fault = err.$fault;
sqsError.time = new Date();

return sqsError;
}

export { SQSError, TimeoutError, isConnectionError, toSQSError };
14 changes: 14 additions & 0 deletions src/timeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { TimeoutResponse } from './types';
import { TimeoutError } from './errors';

function createTimeout(duration: number): TimeoutResponse[] {
let timeout;
const pending = new Promise((_, reject) => {
timeout = setTimeout((): void => {
reject(new TimeoutError());
}, duration);
});
return [timeout, pending];
}

export { createTimeout };
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { SQSClient, Message } from '@aws-sdk/client-sqs';

export interface TimeoutResponse {
timeout: NodeJS.Timeout;
pending: Promise<void>;
}

export interface ConsumerOptions {
queueUrl: string;
attributeNames?: string[];
Expand Down
37 changes: 37 additions & 0 deletions src/validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { ReceiveMessageCommandOutput } from '@aws-sdk/client-sqs';

import { ConsumerOptions } from './types';

const requiredOptions = [
'queueUrl',
// only one of handleMessage / handleMessagesBatch is required
'handleMessage|handleMessageBatch'
];

function assertOptions(options: ConsumerOptions): void {
requiredOptions.forEach((option) => {
const possibilities = option.split('|');
if (!possibilities.find((p) => options[p])) {
throw new Error(
`Missing SQS consumer option [ ${possibilities.join(' or ')} ].`
);
}
});

if (options.batchSize > 10 || options.batchSize < 1) {
throw new Error('SQS batchSize option must be between 1 and 10.');
}

if (
options.heartbeatInterval &&
!(options.heartbeatInterval < options.visibilityTimeout)
) {
throw new Error('heartbeatInterval must be less than visibilityTimeout.');
}
}

function hasMessages(response: ReceiveMessageCommandOutput): boolean {
return response.Messages && response.Messages.length > 0;
}

export { hasMessages, assertOptions };