use crate::generate::{
names,
spec::{
ConcurrencyKind, EndpointSpec, FormSpec, Kind, ProviderKind, SessionAction, StateStyle,
},
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Names {
pub snake: String,
pub pascal: String,
}
impl Names {
pub fn new(name: &str) -> Self {
Self {
snake: names::snake(name),
pascal: names::pascal(name),
}
}
}
#[derive(Clone, Debug)]
pub struct Field {
pub name: String,
pub ty: String,
pub default: Option<String>,
pub rename: Option<String>,
}
#[derive(Clone, Debug)]
pub struct Event {
pub name: String,
pub fields: Vec<Field>,
pub calls: Option<String>,
pub concurrency: Option<ConcurrencyKind>,
}
#[derive(Clone, Debug)]
pub struct Method {
pub name: String,
pub args: Vec<Field>,
pub returns: String,
pub calls: Option<String>,
pub session: Option<(SessionAction, String)>,
}
#[derive(Clone, Debug)]
pub struct Repository {
pub names: Names,
pub methods: Vec<Method>,
}
#[derive(Clone, Debug)]
pub struct Provider {
pub names: Names,
pub kind: ProviderKind,
pub api_base: String,
pub endpoints: Vec<EndpointSpec>,
}
#[derive(Clone, Debug)]
pub struct Model {
pub names: Names,
pub fields: Vec<Field>,
pub id: Option<String>,
pub variants: Vec<Model>,
}
#[derive(Clone, Debug)]
pub struct State {
pub style: StateStyle,
pub status: Vec<String>,
pub fields: Vec<Field>,
pub error: String,
}
impl State {
pub fn has_status(&self, status: &str) -> bool {
self.status.iter().any(|candidate| candidate == status)
}
}
#[derive(Clone, Debug)]
pub struct Plan {
pub feature: Names,
pub kind: Kind,
pub name: Names,
pub concurrency: ConcurrencyKind,
pub events: Vec<Event>,
pub state: State,
pub models: Vec<Model>,
pub ids: Vec<(String, String, String)>,
pub repository: Option<Repository>,
pub provider: Option<Provider>,
pub dtos: Vec<Model>,
pub page: bool,
pub form: Option<FormSpec>,
pub tests: bool,
}
impl Plan {
pub fn error_type(&self) -> &str {
&self.state.error
}
pub fn is_http(&self) -> bool {
self.provider
.as_ref()
.is_some_and(|provider| provider.kind == ProviderKind::Http)
}
pub fn primary_model(&self) -> Option<&Model> {
self.state
.fields
.iter()
.find_map(|field| vec_inner(&field.ty))
.and_then(|inner| self.models.iter().find(|model| model.names.pascal == inner))
.or_else(|| self.models.first())
}
pub fn model(&self, name: &str) -> Option<&Model> {
self.models.iter().find(|model| model.names.pascal == name)
}
pub fn method(&self, name: &str) -> Option<&Method> {
self.repository
.as_ref()
.and_then(|repository| repository.methods.iter().find(|method| method.name == name))
}
pub fn loader(&self) -> Option<(&Method, &Field)> {
let repository = self.repository.as_ref()?;
repository.methods.iter().find_map(|method| {
if !method.args.is_empty() {
return None;
}
self.state
.fields
.iter()
.find(|field| field.ty == method.returns)
.map(|field| (method, field))
})
}
}
pub fn vec_inner(ty: &str) -> Option<String> {
let ty = ty.replace(' ', "");
ty.strip_prefix("Vec<")
.and_then(|rest| rest.strip_suffix('>'))
.map(str::to_string)
}