Skip to content

Commit 4b23d4b

Browse files
authored
dedup body (#2)
* dedup body * merge pub use
1 parent b1a8b87 commit 4b23d4b

File tree

9 files changed

+66
-228
lines changed

9 files changed

+66
-228
lines changed

examples/cron/api/cron.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,7 @@ impl<T: SlackClientHttpConnector + Send + Sync> Lambda<'_, T> {
3333

3434
self.post_message(&message, "#general").await?;
3535

36-
let response = Response::builder().status(StatusCode::OK).body(().into())?;
37-
Ok(response)
36+
Ok(Response::builder().status(StatusCode::OK).body(().into())?)
3837
}
3938
}
4039

examples/nextjs/api/rust.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ pub async fn handler(_req: Request) -> Result<Response<Body>, Error> {
3131

3232
let duration = start.elapsed();
3333

34-
let response = Response::builder()
34+
Ok(Response::builder()
3535
.status(StatusCode::OK)
3636
.header("Content-Type", "application/json")
3737
.body(
@@ -41,8 +41,7 @@ pub async fn handler(_req: Request) -> Result<Response<Body>, Error> {
4141
"time": format!("{:.2?}", duration),
4242
"pi": pi
4343
})
44+
.to_string()
4445
.into(),
45-
)?;
46-
47-
Ok(response)
46+
)?)
4847
}

examples/simple/api/complex.rs

+51-13
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
use runtime_demo::choose_starter;
2+
use serde::{Deserialize, Serialize};
23
use serde_json::json;
34
use vercel_runtime::{
4-
process_request, process_response, run_service, service_fn, Body, Error, Request, Response,
5-
ServiceBuilder, StatusCode,
5+
process_request, process_response, run_service, service_fn, Body, Error, Request, RequestExt,
6+
Response, ServiceBuilder, StatusCode,
67
};
78

89
#[tokio::main]
@@ -22,19 +23,56 @@ async fn main() -> Result<(), Error> {
2223
run_service(handler).await
2324
}
2425

25-
pub async fn handler(_req: Request) -> Result<Response<Body>, Error> {
26-
tracing::info!("Choosing a starter Pokemon");
27-
let starter = choose_starter();
26+
#[derive(Debug, Serialize, Deserialize)]
27+
struct Payload {
28+
trainer_name: String,
29+
}
30+
31+
#[derive(Serialize)]
32+
pub struct APIError {
33+
pub message: &'static str,
34+
pub code: &'static str,
35+
}
36+
37+
impl From<APIError> for Body {
38+
fn from(val: APIError) -> Self {
39+
Body::Text(serde_json::to_string(&val).unwrap())
40+
}
41+
}
2842

29-
let response = Response::builder()
30-
.status(StatusCode::OK)
31-
.header("Content-Type", "application/json")
43+
pub fn bad_request(message: &'static str) -> Result<Response<Body>, Error> {
44+
Ok(Response::builder()
45+
.status(StatusCode::BAD_REQUEST)
46+
.header("content-type", "application/json")
3247
.body(
33-
json!({
34-
"message": format!("I choose you, {}!", starter),
35-
})
48+
APIError {
49+
message,
50+
code: "bad_request",
51+
}
3652
.into(),
37-
)?;
53+
)?)
54+
}
55+
56+
pub async fn handler(req: Request) -> Result<Response<Body>, Error> {
57+
tracing::info!("Choosing a starter Pokemon");
58+
let payload = req.payload::<Payload>();
59+
60+
match payload {
61+
Err(..) => bad_request("Invalid payload"),
62+
Ok(None) => bad_request("Invalid payload"),
63+
Ok(Some(payload)) => {
64+
let starter = choose_starter();
3865

39-
Ok(response)
66+
Ok(Response::builder()
67+
.status(StatusCode::OK)
68+
.header("Content-Type", "application/json")
69+
.body(
70+
json!({
71+
"message": format!("{} says: I choose you, {}!", payload.trainer_name, starter),
72+
})
73+
.to_string()
74+
.into(),
75+
)?)
76+
}
77+
}
4078
}

examples/simple/api/simple.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,14 @@ async fn main() -> Result<(), Error> {
1010
pub async fn handler(_req: Request) -> Result<Response<Body>, Error> {
1111
let starter = choose_starter();
1212

13-
let response = Response::builder()
13+
Ok(Response::builder()
1414
.status(StatusCode::OK)
1515
.header("Content-Type", "application/json")
1616
.body(
1717
json!({
1818
"message": format!("I choose you, {}!", starter),
1919
})
20+
.to_string()
2021
.into(),
21-
)?;
22-
23-
Ok(response)
22+
)?)
2423
}

tsconfig.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,5 @@
1111
"strict": true,
1212
"skipLibCheck": true
1313
},
14-
"exclude": ["node_modules", "dist", "demo"]
14+
"exclude": ["node_modules", "dist", "examples"]
1515
}

vercel_runtime/src/body.rs

-194
This file was deleted.

vercel_runtime/src/lib.rs

+5-8
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,17 @@
1-
mod body;
21
mod request;
32
mod response;
3+
44
use lambda_runtime::LambdaEvent;
55
use request::{VercelEvent, VercelRequest};
66
use response::EventResponse;
77
use std::future::Future;
88
use tracing::{debug, error};
99

10-
pub type Request = lambda_http::http::Request<Body>;
11-
pub type Error = lambda_http::Error;
1210
pub type Event<'a> = LambdaEvent<VercelEvent<'a>>;
13-
pub use body::Body;
14-
pub use lambda_http::http::StatusCode;
15-
pub use lambda_http::service_fn;
16-
pub use lambda_http::tower::ServiceBuilder;
17-
pub use lambda_http::Response;
11+
12+
pub use lambda_http::{
13+
http::StatusCode, service_fn, tower::ServiceBuilder, Body, Error, Request, RequestExt, Response,
14+
};
1815
pub use lambda_runtime::run as run_service;
1916

2017
pub async fn run<T: FnMut(Request) -> F, F: Future<Output = Result<Response<Body>, Error>>>(

vercel_runtime/src/request.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
use crate::body::Body;
21
use lambda_http::http::{self, header::HeaderValue, HeaderMap, Method};
2+
use lambda_http::Body;
33
use serde::de::{Deserializer, Error as DeError, MapAccess, Visitor};
44
use serde_derive::Deserialize;
55
use serde_json::Value;

vercel_runtime/src/response.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
use crate::body::Body;
21
use lambda_http::http::{
32
header::{HeaderMap, HeaderValue},
43
Response,
54
};
5+
use lambda_http::Body;
66
use serde::ser::{Error as SerError, SerializeMap, Serializer};
77
use serde_derive::Serialize;
88

0 commit comments

Comments
 (0)