aws-lambda#SQSEvent TypeScript Examples

The following examples show how to use aws-lambda#SQSEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: helpers.ts    From aws-sam-typescript-layers-example with MIT License 6 votes vote down vote up
export function constructSQSEvent(message: any): SQSEvent {
  return {
    Records: [
      {
        messageId: "d90fd5a5-fd9e-4ab0-979b-97a1e70c9587",
        receiptHandle: "AQEB3Z4KHgpG7c/PG+QzcQ8+lfkZTtoS902r67GNes0Oo4JvcaEzkpTYoUzWTtbkhwbrJcxX36YvNW73oJXiNRnZjKHMkv9348JwBfLc9ES32IrK7w2RTXJ+Odl1mMIJCnuYGaiM61HxymbBRn3MmDHiOHqPytTwYSUNsZWP+OZRWncmPTBjyqrdq1/bItRLAtIM02WR6r3S+YyjCYLO0kKlYs0g4JZAEJ7CD8VXvDJnuDTBFPGv+5a9HaJRsxwF1LdksC5YYdEQ7uScKHm0gZFGLHyifN6S2J3x6vzooSR72gmUx1Bu43U3yu2arbwbykaO+40NjfsxK/Z43cXStWIlV+V7ZX5kJ9YTpqkOKujZtmZ4fYZXcns/WYEiwuw9eoPFaSMdVJyFCPScNlsGvfcHc8IkjXC0TbhV68XJYb7eR6Y=",
        body: JSON.stringify(message),
        attributes: {
          ApproximateReceiveCount: "1",
          SentTimestamp: "1602074535529",
          SenderId: "123456789012",
          ApproximateFirstReceiveTimestamp: "1602074535540"
        },
        messageAttributes: {},
        md5OfBody: "033bd94b1168d7e4f0d644c3c95e35bf",
        eventSource: "aws:sqs",
        eventSourceARN: "arn:aws:sqs:us-east-1:123456789012:WriteQueue-KJAGRBTIIB1Y",
        awsRegion: "us-east-1"
      }
    ]
  }
}
Example #2
Source File: write-item.ts    From aws-sam-typescript-layers-example with MIT License 6 votes vote down vote up
writeItemHandler = async (
    event: SQSEvent,
) => {
    console.info('Received from SQS:', event);

    for (const record of event.Records) {
        const body = JSON.parse(record.body);
        const item = { id: body.id, name: body.name };

        const client = new CustomDynamoClient();
        await client.write(item);

        console.info('Written to DynamoDB:', item)
    }
}
Example #3
Source File: queue-broker.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
handler = async (event: SQSEvent, context: Context): Promise<void> => {
  if (!_applicationContainer) {
    _applicationContainer = ApplicationContainer.instance();
  }

  _applicationContainer.logger.debug('Queue Broker: %o', event);

  // process each record by calling registered handlers for the event type
  for (const record of event.Records) {
    const currentEvent: Event = JSON.parse(record.body);

    // call handlers for this event
    for (const handlerName of HandlesEventService.getHandlers(currentEvent.$name)) {
      await callHandler(currentEvent, handlerName);
    }
  };
}
Example #4
Source File: processActivity.test.ts    From MDDL with MIT License 6 votes vote down vote up
data: SQSEvent = {
  Records: [
    {
      attributes: {
        MessageGroupId: '8692AA86-81A8-4806-A1BA-F024B36BDB98',
        ApproximateReceiveCount: '1',
        SentTimestamp: '123456789',
        SenderId: 'DE7718E4-0B69-455E-9F9B-3C663653CF7B',
        ApproximateFirstReceiveTimestamp: '123456789',
      },
      messageId: '2903B5CC-A7C2-4185-9C6A-EA0636BC7AFD',
      body: JSON.stringify({
        field1: 'value1',
        field2: 'value2',
      }),
      awsRegion: 'us-east-1',
      eventSource: 'test',
      eventSourceARN: 'aws:::test::resource',
      md5OfBody: '1234567890',
      messageAttributes: {},
      receiptHandle: 'test',
    },
  ],
}
Example #5
Source File: processActivity.ts    From MDDL with MIT License 5 votes vote down vote up
handler = wrapAsyncHandler(
  async (event: SQSEvent) => {
    // group by message group ID which is going to be our log stream name (should be the users ID)
    const groupedRecords = groupBy(
      event.Records,
      (r) => r.attributes.MessageGroupId,
    )

    // then process each group of messages
    for (const logStreamName in groupedRecords) {
      // get the records in the group
      const records = groupedRecords[logStreamName]
      const sequenceToken = await getSequenceToken(logStreamName)

      try {
        // try to put the events into the log stream, using the latest sequence token we know about
        const nextSequenceToken = await putLogEvents(
          {
            logGroupName,
            logStreamName,
          },
          records.map((r) => ({
            // these are both unix timestamps in milliseconds, but the SQS message is given as a string ¯\_(ツ)_/¯
            timestamp: parseInt('' + r.attributes.SentTimestamp),
            message: r.body,
          })),
          sequenceToken,
        )
        setSequenceToken(logStreamName, nextSequenceToken)
      } catch (ex) {
        logger.error(ex, 'An error occurred putting log events')
        // clean up sequence token as we may have cached the wrong value
        deleteSequenceToken(logStreamName)
        // we need to throw so that unprocessed messages are put back on the queue
        throw ex
      }
      // clean up messages in this group
      await deleteMessages(queueUrl, records)
    }
    return event.Records.length
  },
  {
    rethrowAfterCapture: true,
  },
)
Example #6
Source File: processSendRequest.ts    From MDDL with MIT License 5 votes vote down vote up
handler = wrapAsyncHandler(
  async (event: SQSEvent) => {
    for (const record of event.Records) {
      const { error, value: sendRequest } = parseAndValidate<SendRequest>(
        record.body,
        sendRequestSchema,
      )
      if (error) {
        logger.error(
          error,
          'Error occurred validating record. Message will be removed from queue.',
          record,
        )
        await deleteMessages(getQueueUrl(), [record])
        continue
      }

      // read out message data
      const { toAddresses, template, data, subject } = sendRequest

      // send the emails individually to each recipient
      await Promise.all(
        toAddresses.map((to) =>
          sendEmail({
            template,
            destination: {
              ToAddresses: [to],
            },
            subject,
            data,
          }),
        ),
      )
      await deleteMessages(getQueueUrl(), [record])
    }
  },
  {
    rethrowAfterCapture: true,
  },
)