Handler

The handler performs the same logic as the original example, but it is completely rewritten with Rust and the lambda_runtime crate. Look at the implementation of the handler function:

fn handler(event: Request, _: Context) -> Result<Response, HandlerError> {
let region = Region::default();
let client = DynamoDbClient::new(region);
let username = event
.request_context
.authorizer
.claims
.get("cognito:username")
.unwrap()
.to_owned();
debug!("USERNAME: {}", username);
let ride_id = Uuid::new_v4().to_string();
let request: RequestBody = serde_json::from_str(&event.body).unwrap();
let unicorn = find_unicorn(&request.pickup_location);
record_ride(&client, &ride_id, &username, &unicorn).unwrap();
let body = ResponseBody {
ride_id: ride_id.clone(),
unicorn_name: unicorn.name.clone(),
unicorn,
eta: "30 seconds".into(),
rider: username.clone(),
};
let mut headers = HashMap::new();
headers.insert("Access-Control-Allow-Origin".into(), "*".into());
let body = serde_json::to_string(&body).unwrap();
let resp = Response {
status_code: 201,
body,
headers,
};
Ok(resp)
}

Initially, this function creates a connection to DynamoDB using the default Region value, which initially reads environment variables to get an actual value, and if it doesn't find a region, it uses the us-east-1 region. Then, the handler extracts a username provided by Cognito that we will use to authorize users and won't implement user registration manually.

Then we generate the unique ID of a ride and extract the body of a request that is provided by a JSON string. You can't declare a complete Request struct, you have to parse it with two steps. The first uses the lambda! macro, and the second uses the serde_json::from_str function call. Then, we call the find_unicorn function, which we will implement later, and add a record to a database using the record_ride function call, which we will implement later in this section.

When the record is added, we construct a response in two steps. First, we create the body of a response, and then we wrap it with extra values. We have to do this wrapping because we will use API Gateway to call the lambda with an external application shared by S3.

Now we can have a look at structs that we need.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.78.102