Skip to content

Instantly share code, notes, and snippets.

@embano1
Created October 3, 2022 11:31
Show Gist options
  • Save embano1/f5edd8b724ac4409f30781d94d86d4de to your computer and use it in GitHub Desktop.
Save embano1/f5edd8b724ac4409f30781d94d86d4de to your computer and use it in GitHub Desktop.
CloudEvents TypeScript AWS Lambda SQS Example
import {SQSEvent, SQSHandler} from 'aws-lambda';
import {CloudEvent} from 'cloudevents';
export const handler: SQSHandler = async (events: SQSEvent) => {
events.Records.forEach(e => {
const ce: CloudEvent<string> = new CloudEvent<string>(JSON.parse(e.body));
console.log(ce);
});
};
const ce = `
{
"specversion" : "1.0",
"type" : "com.github.pull.create",
"source" : "https://github.com/cloudevents/spec/pull/123",
"id" : "A234-1234-1234",
"time" : "2020-04-05T17:31:00Z",
"comexampleextension1" : "value",
"comexampleextension2" : {
"othervalue": 5
},
"contenttype" : "application/cloudevents+json",
"data" : "hello world"
}
`;
const input: 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: ce,
awsRegion: 'us-east-1',
eventSource: 'test',
eventSourceARN: 'aws:::test::resource',
md5OfBody: '1234567890',
messageAttributes: {},
receiptHandle: 'test',
},
],
};
import {Context} from 'aws-lambda';
const mockedContext: Context = {
callbackWaitsForEmptyEventLoop: false,
functionName: 'mocked',
functionVersion: 'mocked',
invokedFunctionArn: 'mocked',
memoryLimitInMB: 'mocked',
awsRequestId: 'mocked',
logGroupName: 'mocked',
logStreamName: 'mocked',
getRemainingTimeInMillis(): number {
return 999;
},
done(error?: Error, result?: any): void {
return;
},
fail(error: Error | string): void {
return;
},
succeed(messageOrObject: any): void {
return;
},
};
handler(input, mockedContext, () => {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment