teo_runtime/handler/group/
builder.rs1use std::collections::BTreeMap;
2use std::sync::{Arc, Mutex};
3use maplit::btreemap;
4use teo_parser::ast::handler::HandlerInputFormat;
5use teo_parser::r#type::Type;
6use crate::app::data::AppData;
7use crate::handler::ctx_argument::HandlerCtxArgument;
8use crate::handler::{Group, Handler, handler};
9use crate::handler::group::group;
10use hyper::Method;
11use crate::middleware::next::Next;
12use crate::request::Request;
13use crate::traits::named::Named;
14use crate::utils::next_path;
15
16#[derive(Debug, Clone)]
17pub struct Builder {
18 inner: Arc<Inner>
19}
20
21#[derive(Debug)]
22struct Inner {
23 pub path: Vec<String>,
24 pub(crate) handlers: Arc<Mutex<BTreeMap<String, Handler>>>,
25 pub app_data: AppData,
26
27}
28
29impl Builder {
30
31 pub fn new(path: Vec<String>, app_data: AppData) -> Self {
32 Self {
33 inner: Arc::new(Inner {
34 path,
35 handlers: Arc::new(Mutex::new(btreemap! {})),
36 app_data,
37 })
38 }
39 }
40
41 pub fn path(&self) -> &Vec<String> {
42 &self.inner.path
43 }
44
45 pub fn handler(&self, name: &str) -> Option<Handler> {
46 let handlers = self.inner.handlers.lock().unwrap();
47 handlers.get(name).cloned()
48 }
49
50 pub fn insert_handler(&self, name: &str, handler: Handler) {
51 let mut handlers = self.inner.handlers.lock().unwrap();
52 handlers.insert(name.to_owned(), handler);
53 }
54
55 pub fn define_handler<T, F>(&self, name: &str, body: F) where T: 'static, F: 'static + HandlerCtxArgument<T> {
56 let body = Arc::new(body);
57 let handler = Handler {
58 inner: Arc::new(handler::Inner {
59 namespace_path: {
60 let mut result = self.inner.path.clone();
61 result.pop();
62 result
63 },
64 input_type: Type::Undetermined,
65 output_type: Type::Undetermined,
66 nonapi: false,
67 format: HandlerInputFormat::Json,
68 path: next_path(self.path(), name),
69 ignore_prefix: false,
70 method: Method::POST,
71 interface: None,
72 url: None,
73 call: Next::new(move |request: Request| {
74 let body = body.clone();
75 async move {
76 body.call(request).await
77 }
78 }),
79 })
80 };
81 let mut handlers = self.inner.handlers.lock().unwrap();
82 handlers.insert(name.to_owned(), handler);
83 }
84
85 pub fn app_data(&self) -> &AppData {
86 &self.inner.app_data
87 }
88
89 pub fn build(self) -> Group {
90 Group {
91 inner: Arc::new(group::Inner {
92 path: self.path().clone(),
93 handlers: self.inner.handlers.lock().unwrap().clone(),
94 })
95 }
96 }
97}
98
99impl Named for Builder {
100 fn name(&self) -> &str {
101 self.inner.path.last().unwrap().as_str()
102 }
103}