|
| 1 | +use lambda_runtime::{service_fn, Error, LambdaEvent}; |
| 2 | +use pizza_lib::Pizza; |
| 3 | +use serde_json::{json, Value}; |
| 4 | + |
| 5 | +struct SQSManager { |
| 6 | + client: aws_sdk_sqs::Client, |
| 7 | + queue_url: String, |
| 8 | +} |
| 9 | + |
| 10 | +impl SQSManager { |
| 11 | + fn new(client: aws_sdk_sqs::Client, queue_url: String) -> Self { |
| 12 | + Self { client, queue_url } |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +#[tokio::main] |
| 17 | +async fn main() -> Result<(), Error> { |
| 18 | + tracing_subscriber::fmt() |
| 19 | + .with_max_level(tracing::Level::INFO) |
| 20 | + .with_target(false) |
| 21 | + .with_ansi(false) |
| 22 | + .without_time() |
| 23 | + .init(); |
| 24 | + |
| 25 | + // read the queue url from the environment |
| 26 | + let queue_url = std::env::var("QUEUE_URL").expect("could not read QUEUE_URL"); |
| 27 | + // build the config from environment variables (fed by AWS Lambda) |
| 28 | + let config = aws_config::from_env().load().await; |
| 29 | + // create our SQS Manager |
| 30 | + let sqs_manager = SQSManager::new(aws_sdk_sqs::Client::new(&config), queue_url); |
| 31 | + let sqs_manager_ref = &sqs_manager; |
| 32 | + |
| 33 | + // no need to create a SQS Client for each incoming request, let's use a shared state |
| 34 | + let handler_func_closure = |event: LambdaEvent<Value>| async move { |
| 35 | + process_event(event, sqs_manager_ref).await |
| 36 | + }; |
| 37 | + lambda_runtime::run(service_fn(handler_func_closure)).await?; |
| 38 | + Ok(()) |
| 39 | +} |
| 40 | + |
| 41 | +async fn process_event(_: LambdaEvent<Value>, sqs_manager: &SQSManager) -> Result<(), Error> { |
| 42 | + // let's create our pizza |
| 43 | + let message = Pizza { |
| 44 | + name: "margherita".to_string(), |
| 45 | + toppings: vec![ |
| 46 | + "San Marzano Tomatoes".to_string(), |
| 47 | + "Fresh Mozzarella".to_string(), |
| 48 | + "Basil".to_string(), |
| 49 | + ], |
| 50 | + }; |
| 51 | + // send our message to SQS |
| 52 | + sqs_manager |
| 53 | + .client |
| 54 | + .send_message() |
| 55 | + .queue_url(&sqs_manager.queue_url) |
| 56 | + .message_body(json!(message).to_string()) |
| 57 | + .send() |
| 58 | + .await?; |
| 59 | + |
| 60 | + Ok(()) |
| 61 | +} |
0 commit comments