-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
112 lines (94 loc) · 2.78 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use wasmbus_rpc::actor::prelude::*;
use wasmcloud_interface_httpserver::{
HttpRequest, HttpResponse, HttpServer, HttpServerReceiver,
};
mod logger;
#[derive(Debug, Default, Actor, HealthResponder)]
#[services(Actor, HttpServer)]
struct VerbalcodeActor {}
#[async_trait]
impl HttpServer for VerbalcodeActor {
async fn handle_request(
&self,
ctx: &Context,
req: &HttpRequest,
) -> RpcResult<HttpResponse> {
logger::log(format!("Request = {:?}", req)).await;
handle_http_request(ctx, req).await
}
}
use serde_urlencoded as urlencoded;
use key_value_store::KeyValueStore;
mod key_value_store;
mod responder;
mod twilio {
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Payload {
pub body: String,
pub from: String,
}
}
async fn handle_http_request(
ctx: &Context,
req: &HttpRequest,
) -> RpcResult<HttpResponse> {
let payload = &req.body.as_slice();
let payload: twilio::Payload = urlencoded::from_bytes(payload).unwrap();
let mut store = new_store(ctx);
let body = respond(payload.body, payload.from, &mut store).await;
let mut resp = HttpResponse {
body: body.as_bytes().to_vec(),
..Default::default()
};
resp.header
.entry("content-type".to_string())
.or_insert_with(|| vec!["text/plain".to_string()]);
logger::log(format!("Response = {:?}, Body = {}", resp, body)).await;
Ok(resp)
}
#[cfg(not(test))]
async fn respond<T: KeyValueStore>(
prompt: String,
prompter: String,
store: &mut T,
) -> String {
responder::handle(prompt, prompter, store).await
}
#[cfg(test)]
async fn respond<T: KeyValueStore>(
prompt: String,
prompter: String,
_store: &mut T,
) -> String {
format!("from: {}, body: {}", prompter, prompt)
}
#[cfg(target_arch = "wasm32")]
fn new_store(ctx: &Context) -> key_value_store::Actor {
key_value_store::Actor::new(ctx)
}
#[cfg(not(target_arch = "wasm32"))]
fn new_store(_ctx: &Context) -> key_value_store::InMemory {
key_value_store::InMemory::new()
}
#[cfg(test)]
mod test {
use crate::handle_http_request;
use serde_json as json;
use std::fs;
use wasmbus_rpc::actor::prelude::*;
use wasmcloud_interface_httpserver::HttpRequest;
#[tokio::test]
async fn can_handle_http_request() {
let req = fs::read_to_string("test/fixtures/request_1.json").unwrap();
let req: HttpRequest = json::from_str(&req).unwrap();
let ctx: Context = Default::default();
let resp = handle_http_request(&ctx, &req).await.unwrap();
assert_eq!(resp.status_code, 200);
assert_eq!(
String::from_utf8(resp.body).unwrap(),
"from: +14108025604, body: test".to_string()
);
}
}