And we have several use cases across microservices like that: a customer create orders with some products and, if the payment is successful,
the products should be delivered to the customer. So the we can perform the whole process with events and events is more understandable for customers also. These could be flow of events like;
a customer creates an order
the customer receives a payment request
if the payment is successful the stock is updated and the order is delivered
if the payment in not successful, rollback the order and set order status is not completed.
This is more humanly readable and, if a new business requirement appears, it is easier to change the flow.
xxxxxxxxxx
import { PutEventsCommand } from “@aws-sdk/client-eventbridge”;
import { ebClient } from “./eventBridgeClient.js”;
export const handler = async (event) => {
console.log(“event:”, JSON.stringify(event, undefined, 2));
// pseo code
// 1- redirect incoming http request to correct path
// 2- get request body payload which includes event data
// 3- publish message to Amazon EventBridge Custom Eventbus with using eventbridge sdk package
// 4- return back snyc basket payload to the api gateway
try {
// 1- redirect incoming http request to correct path
if (event.httpMethod != ‘POST’) {
throw new Error(`Http Method should be POST. You are requesting : “${event.httpMethod}”`);
}
// 2- get request body payload which includes event data
// expected request payload : { “item”:”iphone”, “price”:150, “detailtype”:”CheckoutBasket”, “source”: “com.swn.basket.checkoutbasket”
const basketRequest = JSON.parse(event.body);
if (basketRequest == null || basketRequest.detailtype == null) {
throw new Error(`basket detail-type should exist in basketRequest: “${basketRequest}”`);
}
// 3- publish message to Amazon EventBridge Custom Eventbus with using eventbridge sdk package
const params = {
Entries: [
{
Source: basketRequest.source,
Detail: JSON.stringify(basketRequest),
DetailType: basketRequest.detailtype,
Resources: [ ],
EventBusName: ‘CheckoutBasketEventBus’
},
],
};
const data = await ebClient.send(new PutEventsCommand(params));
console.log(“Success, event sent; requestID:”, data);
// 4- return back snyc basket payload to the api gateway
return {
statusCode: 200,
body: JSON.stringify({
message: `Successfully finished basket operation: “${basketRequest}”`,
body: data
})
};
} catch (e) {
console.error(e);
return {
statusCode: 500,
body: JSON.stringify({
message: “Failed to perform operation.”,
errorMsg: e.message,
errorStack: e.stack,
})
};
}
};