|
| 1 | +import { |
| 2 | + GetQueueUrlCommand, |
| 3 | + SQSClient, |
| 4 | + SendMessageBatchCommand, |
| 5 | + SendMessageBatchRequestEntry, |
| 6 | +} from '@aws-sdk/client-sqs'; |
| 7 | +import { v4 } from 'uuid'; |
| 8 | +import { getPrefixWithProcessingPriority } from '../utils/getPrefixWithProcessingPriority'; |
| 9 | +import { StatementProcessingPriority } from '../../../enums/statementProcessingPriority.enum'; |
| 10 | +import FacadeConfig from '../utils/sqsEvents/FacadeConfig'; |
| 11 | +import { STATEMENT_QUEUE } from '../utils/constants'; |
| 12 | +import Signature from './Signature'; |
| 13 | + |
| 14 | +const MAX_BATCH_SIZE = 10; |
| 15 | + |
| 16 | +let queueUrl: string | undefined; |
| 17 | + |
| 18 | +const publishMessages = async (sqsClient: SQSClient, statementProperties: string[]) => { |
| 19 | + const statementPropertiesBatchRequest = statementProperties.map( |
| 20 | + (statementProperty): SendMessageBatchRequestEntry => ({ |
| 21 | + Id: v4(), |
| 22 | + MessageBody: statementProperty, |
| 23 | + }), |
| 24 | + ); |
| 25 | + |
| 26 | + for (let index = 0; index < statementPropertiesBatchRequest.length; index += MAX_BATCH_SIZE) { |
| 27 | + await sqsClient.send( |
| 28 | + new SendMessageBatchCommand({ |
| 29 | + QueueUrl: queueUrl, |
| 30 | + Entries: statementPropertiesBatchRequest.slice(index, index + MAX_BATCH_SIZE), |
| 31 | + }), |
| 32 | + ); |
| 33 | + } |
| 34 | +}; |
| 35 | + |
| 36 | +const getQueueUrl = async ( |
| 37 | + sqsClient: SQSClient, |
| 38 | + prefix: string, |
| 39 | + priority: StatementProcessingPriority, |
| 40 | + isQueuePriorityEnabled: boolean, |
| 41 | +) => { |
| 42 | + if (queueUrl) { |
| 43 | + return queueUrl; |
| 44 | + } |
| 45 | + |
| 46 | + const prefixWithPriority = getPrefixWithProcessingPriority( |
| 47 | + prefix, |
| 48 | + priority, |
| 49 | + isQueuePriorityEnabled, |
| 50 | + ); |
| 51 | + |
| 52 | + const getQueueUrlCommand = new GetQueueUrlCommand({ |
| 53 | + QueueName: `${prefixWithPriority}_${STATEMENT_QUEUE}`, |
| 54 | + }); |
| 55 | + |
| 56 | + const commandResult = await sqsClient.send(getQueueUrlCommand); |
| 57 | + |
| 58 | + queueUrl = commandResult.QueueUrl; |
| 59 | + |
| 60 | + return queueUrl; |
| 61 | +}; |
| 62 | + |
| 63 | +export default (config: FacadeConfig): Signature => { |
| 64 | + return async ({ statementProperties, priority }) => { |
| 65 | + const sqsClient = await config.client(); |
| 66 | + |
| 67 | + await getQueueUrl(sqsClient, config.prefix, priority, config.isQueuePriorityEnabled); |
| 68 | + await publishMessages(sqsClient, statementProperties); |
| 69 | + }; |
| 70 | +}; |
0 commit comments