ayun_console/support/
service.rs1use crate::{
2 support::{commands, Command},
3 Console,
4};
5use ayun_config::{config, support::config};
6use ayun_core::{
7 traits::{ApplicationTrait, ServiceTrait},
8 Result,
9};
10
11impl ServiceTrait for Console {
12 type Item = Command;
13
14 fn new() -> Self {
15 Self::default()
16 }
17
18 fn register(mut self, command: Self::Item) -> Self {
19 self.commands
20 .insert(command.name().to_string(), command.command().clone());
21 self.closures
22 .insert(command.name().to_string(), command.handler().clone());
23
24 self
25 }
26
27 fn init<A: ApplicationTrait>() -> Self {
28 let mut console = (&A::with_console() as &dyn std::any::Any)
29 .downcast_ref::<Self>()
30 .cloned()
31 .unwrap_or(Self::default());
32
33 #[cfg(feature = "command-make")]
34 {
35 console = console.register(Command::new::<A, commands::Make>());
36 }
37
38 #[cfg(feature = "command-migrate")]
39 {
40 console = console.register(Command::new::<A, commands::Migrate>());
41 }
42
43 #[cfg(feature = "command-queue")]
44 {
45 console = console.register(Command::new::<A, commands::Queue>());
46 }
47
48 #[cfg(feature = "command-server")]
49 {
50 console = console.register(Command::new::<A, commands::Server>());
51 }
52
53 #[cfg(feature = "command-schedule")]
54 {
55 console = console.register(Command::new::<A, commands::Schedule>());
56 }
57
58 #[cfg(feature = "command-status")]
59 {
60 console = console.register(Command::new::<A, commands::Status>());
61 }
62
63 console = console.register(Command::new::<A, commands::Publish>());
64
65 console
66 }
67
68 fn run(self) -> Result<()> {
69 let environment = config::<config::App>("app")?.environment;
70
71 let span = tracing::debug_span!("console",environment=%environment);
72 let _enter = span.enter();
73
74 let commands = self.inner.subcommands(self.commands.values());
75
76 match commands.clone().get_matches().subcommand() {
77 Some((name, arg_matches)) => {
78 if let Some(closure) = self.closures.get(name) {
79 if let Some(err) = closure(arg_matches.to_owned()).err() {
80 tracing::error!("[command] `{}` handle error: {}", name, err);
81 }
82 }
83 }
84 None => commands.clone().print_help()?,
85 }
86
87 Ok(())
88 }
89}