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

Add aws-node-eventbridge #605

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ serverless install -u https://github.com/serverless/examples/tree/master/folder-
| [Aws Node Dynamodb Backup](https://github.com/serverless/examples/tree/master/aws-node-dynamodb-backup) <br/> Serverless DynamoDB changes backed up to S3 | nodeJS |
| [Aws Env Variables Encrypted In A File](https://github.com/serverless/examples/tree/master/aws-node-env-variables-encrypted-in-a-file) <br/> Serverless example managing secrets in an encrypted file | nodeJS |
| [Aws Env Variables](https://github.com/serverless/examples/tree/master/aws-node-env-variables) <br/> This example demonstrates how to use environment variables for AWS Lambdas. | nodeJS |
| [Aws Node Eventbridge](https://github.com/serverless/examples/tree/master/aws-node-eventbridge) <br/> Example demonstrates how to add events and listener rules to AWS Eventbridge | nodeJS |
| [Aws Node Express Api](https://github.com/serverless/examples/tree/master/aws-node-express-api) | nodeJS |
| [Aws Node Express Dynamodb Api](https://github.com/serverless/examples/tree/master/aws-node-express-dynamodb-api) | nodeJS |
| [Aws Fetch File And Store In S3](https://github.com/serverless/examples/tree/master/aws-node-fetch-file-and-store-in-s3) <br/> Fetch an image from remote source (URL) and then upload the image to a S3 bucket. | nodeJS |
Expand Down
2 changes: 2 additions & 0 deletions aws-node-eventbridge/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.serverless
53 changes: 53 additions & 0 deletions aws-node-eventbridge/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<!--
title: 'AWS Serverless EventBridge examples in NodeJS'
description: 'This example demonstrates how to add events to an EventBridge bus and then trigger rules.'
layout: Doc
framework: v2
platform: AWS
language: nodeJS
authorLink: 'https://github.com/WayneGreeley'
authorName: 'Wayne Greeley'
authorAvatar: 'https://avatars.githubusercontent.com/u/28657024?s=60&v=4'
-->
# Serverless EventBridge example

This example demonstrates how to add events to the default bus and a custom bus and how to trigger event rules.

## Use-case

De-coupling microservices using the AWS EventBridge service

## Setup

```bash
npm i -g serverless
npm i
sls deploy
```

### Send a message to Alice Lambda

```bash
curl -X POST -H "Content-Type:application/json" https://XXXXXXX.execute-api.us-east-1.amazonaws.com/alice
--data '{ "messageSentToAlice": "Learn Serverless" }'
```

Example Result:
```bash
{"message":"Alice was called"}
```

Alice leaves an event on a custom bus.
Bob is listening for events that Alice creates.

Dave is a schedule cron Lambda that runs every 10 minutes.
Dave picks a random number between 1 and 151 and fetches the Pokemon from PokeAPI for that random number.

Eve has lots of rules she is listening for on the default EventBridge bus including scheduled events like Dave.

This example if a combination of lessons learned from Phillip Muns blog:
https://www.serverless.com/blog/eventbridge-use-cases-and-tutorial/

and Marcia Villalba YouTube video:
https://www.youtube.com/watch?v=VYtBXdf53b4

64 changes: 64 additions & 0 deletions aws-node-eventbridge/handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict';

const AWS = require('aws-sdk');
const fetch = require('node-fetch');

const eventbridge = new AWS.EventBridge({ apiVersion: '2015-10-07' });

function putEvent(event) {
const detail = { name: 'Message',
messageSentToAlice: event.body,
};

const params = {
Entries: [
{
EventBusName: 'custom-decouple-events',
Detail: JSON.stringify(detail),
DetailType: 'Triggering_Bob',
Source: 'alice.trigger',
},
],
};

return eventbridge.putEvents(params).promise();
}

module.exports.alice = async (event) => {
console.log(`event:${JSON.stringify(event)}`);

const data = await putEvent(event);
console.log(data);

return {
statusCode: 200,
body: JSON.stringify({ message: 'Alice was called' }),
};
};

module.exports.bob = async (event) => {
console.log(`event:${JSON.stringify(event)}`);

const eventDetail = event.detail.messageSentToAlice;
const messageSentFromAlice = JSON.parse(eventDetail).messageSentToAlice;
console.log(`messageSentFromAlice:${messageSentFromAlice}`);
};

function getRandomIntInclusive(min, max) {
const mini = Math.ceil(min);
const maxi = Math.floor(max);
return Math.floor((Math.random() * ((maxi - mini) + 1)) + mini);
}

module.exports.eve = async (event) => {
console.log(`event:${JSON.stringify(event)}`);
};

module.exports.dave = async (event) => {
console.log(`event:${JSON.stringify(event)}`);
const pokemonNumber = getRandomIntInclusive(1, 151);
const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonNumber}`);
const json = await res.json();
console.log('responseJSON:', JSON.stringify(json));
return json;
};
10 changes: 10 additions & 0 deletions aws-node-eventbridge/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "aws-node-eventbridge",
"version": "1.0.0",
"description": "Example demonstrates how to add events and listener rules to AWS Eventbridge",
"author": "",
"license": "MIT",
"dependencies": {
"node-fetch": "^2.6.1"
}
}
53 changes: 53 additions & 0 deletions aws-node-eventbridge/serverless.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
service: aws-node-eventbridge

provider:
name: aws
runtime: nodejs14.x

iamRoleStatements:
- Effect: "Allow"
Action:
- "events:PutEvents"
Resource: "*"

functions:
alice:
handler: handler.alice
events:
- httpApi:
method: POST
path: /alice
bob:
handler: handler.bob
events:
- eventBridge:
eventBus: custom-decouple-events
pattern:
source:
- alice.trigger
detail-type:
- Triggering_Bob
detail:
name:
- "Message"
eve:
handler: handler.eve
events:
- eventBridge:
pattern:
source:
- aws.apigateway
- aws.cloudtrail
- aws.cloudwatch
- aws.dynamodb
- aws.ec2
- aws.events
- aws.iam
- aws.kms
- aws.logs
- aws.secretsmanager
dave:
handler: handler.dave
events:
- eventBridge:
schedule: rate(10 minutes)
Loading