working proto
This commit is contained in:
48
src/app.rs
48
src/app.rs
@@ -1,34 +1,34 @@
|
||||
use crate::values::FormValues;
|
||||
use crate::todo::TodoApp;
|
||||
use leptos::prelude::*;
|
||||
use leptos::*;
|
||||
use leptos_meta::*;
|
||||
use leptos_router::{
|
||||
components::{FlatRoutes, Route, Router},
|
||||
ParamSegment, SsrMode, StaticSegment,
|
||||
};
|
||||
use leptos_router::*;
|
||||
|
||||
use crate::routes::*;
|
||||
|
||||
#[component]
|
||||
pub fn App() -> impl IntoView {
|
||||
// Provides context that manages stylesheets, titles, meta tags, etc.
|
||||
provide_meta_context();
|
||||
let fallback = || view! { "Page not found." }.into_view();
|
||||
|
||||
view! {
|
||||
<Router>
|
||||
<nav class="flex gap-5 px-2 py-1 ">
|
||||
<a href="/">Home</a>
|
||||
<a href="/formulaire">Formulaire</a>
|
||||
<a href="/todos">Todos</a>
|
||||
</nav>
|
||||
<main>
|
||||
<FlatRoutes fallback>
|
||||
<Route path=StaticSegment("/") view=Home ssr=SsrMode::Async/>
|
||||
<Route path=StaticSegment("/formulaire") view=FormValues ssr=SsrMode::Async />
|
||||
<Route path=StaticSegment("/todos") view=TodoApp ssr=SsrMode::Async />
|
||||
<Route path=StaticSegment("/*any") view=NotFound ssr=SsrMode::Async/>
|
||||
</FlatRoutes>
|
||||
</main>
|
||||
</Router>
|
||||
<Stylesheet href="/pkg/rust_leptos.css"/>
|
||||
|
||||
<Title text="Welcome to Leptos"/>
|
||||
|
||||
<div class="dark:bg-slate-950 dark:text-white h-screen flex flex-col">
|
||||
<Router>
|
||||
<nav class="flex gap-5 px-2 py-1 ">
|
||||
<a href="/">Home</a>
|
||||
<a href="/formulaire">Formulaire</a>
|
||||
</nav>
|
||||
<main class="flex-1">
|
||||
<Routes>
|
||||
<Route path="/" view=move || view! { <Home/> }/>
|
||||
<Route path="/formulaire" view=move || view! { <FormValues/> }/>
|
||||
//<Route path="/*any" view=move || view! { <NotFound/> }/>
|
||||
</Routes>
|
||||
</main>
|
||||
<footer>Footer</footer>
|
||||
</Router>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
26
src/database.rs
Normal file
26
src/database.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
static DB: std::sync::OnceLock<sqlx::MySqlPool> = std::sync::OnceLock::new();
|
||||
|
||||
async fn create_pool() -> sqlx::MySqlPool {
|
||||
let database_url = std::env::var("DATABASE_URL").expect("no database url specify");
|
||||
dbg!(&database_url);
|
||||
let pool = sqlx::mysql::MySqlPoolOptions::new()
|
||||
.max_connections(4)
|
||||
.connect(database_url.as_str())
|
||||
.await
|
||||
.expect("could not connect to database_url");
|
||||
|
||||
sqlx::migrate!()
|
||||
.run(&pool)
|
||||
.await
|
||||
.expect("migrations failed");
|
||||
|
||||
pool
|
||||
}
|
||||
|
||||
pub async fn init_db() -> Result<(), sqlx::Pool<sqlx::MySql>> {
|
||||
DB.set(create_pool().await)
|
||||
}
|
||||
|
||||
pub fn get_db<'a>() -> &'a sqlx::MySqlPool {
|
||||
DB.get().expect("database unitialized")
|
||||
}
|
||||
16
src/lib.rs
16
src/lib.rs
@@ -1,18 +1,18 @@
|
||||
pub mod app;
|
||||
pub mod todo;
|
||||
pub mod values;
|
||||
#[cfg(feature = "ssr")]
|
||||
pub(crate) mod database;
|
||||
pub(crate) mod models;
|
||||
pub(crate) mod routes;
|
||||
#[cfg(feature = "ssr")]
|
||||
pub mod setup;
|
||||
|
||||
#[cfg(feature = "hydrate")]
|
||||
#[wasm_bindgen::prelude::wasm_bindgen]
|
||||
pub fn hydrate() {
|
||||
use app::App;
|
||||
use todo::TodoApp;
|
||||
use leptos::*;
|
||||
|
||||
use crate::app::*;
|
||||
use crate::todo::*;
|
||||
use crate::values::*;
|
||||
console_error_panic_hook::set_once();
|
||||
_ = console_log::init_with_level(log::Level::Debug);
|
||||
|
||||
leptos::mount::hydrate_body(App);
|
||||
mount_to_body(move || view! { <App/> });
|
||||
}
|
||||
|
||||
79
src/main.rs
79
src/main.rs
@@ -1,75 +1,12 @@
|
||||
mod todo;
|
||||
mod values;
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
mod ssr {
|
||||
pub use actix_files::Files;
|
||||
pub use actix_web::*;
|
||||
pub use leptos::prelude::*;
|
||||
pub use leptos_actix::{generate_route_list, LeptosRoutes};
|
||||
pub use rust_leptos::app::*;
|
||||
|
||||
#[get("/style.css")]
|
||||
pub async fn css() -> impl Responder {
|
||||
actix_files::NamedFile::open_async("./style/output.css").await
|
||||
}
|
||||
|
||||
#[get("/favicon.ico")]
|
||||
pub async fn favicon() -> impl Responder {
|
||||
actix_files::NamedFile::open_async("./target/site/favicon.ico").await
|
||||
}
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
rust_leptos::setup::init_app(None).await;
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
use self::{ssr::*, values::ssr::*};
|
||||
|
||||
use leptos_meta::*;
|
||||
|
||||
let mut conn = db().await.expect("couldn't connect to DB");
|
||||
sqlx::migrate!()
|
||||
.run(&mut conn)
|
||||
.await
|
||||
.expect("could not run SQLx migrations");
|
||||
|
||||
let conf = get_configuration(None).unwrap();
|
||||
let addr = conf.leptos_options.site_addr;
|
||||
println!("listening on http://{}", &addr);
|
||||
|
||||
HttpServer::new(move || {
|
||||
// Generate the list of routes in your Leptos App
|
||||
let routes = generate_route_list(App);
|
||||
let leptos_options = &conf.leptos_options;
|
||||
let site_root = &leptos_options.site_root;
|
||||
|
||||
App::new()
|
||||
.service(css)
|
||||
.leptos_routes(routes, {
|
||||
let leptos_options = leptos_options.clone();
|
||||
move || {
|
||||
use leptos::prelude::*;
|
||||
view! {
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<Stylesheet href="/pkg/rust_leptos.css"/>
|
||||
<AutoReload options=leptos_options.clone() />
|
||||
<HydrationScripts options=leptos_options.clone()/>
|
||||
<MetaTags/>
|
||||
</head>
|
||||
<body class="dark:bg-slate-900 dark:text-gray-50">
|
||||
<App/>
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
}})
|
||||
.service(Files::new("/", site_root))
|
||||
.wrap(middleware::Compress::default())
|
||||
})
|
||||
.bind(&addr)?
|
||||
.run()
|
||||
.await
|
||||
#[cfg(not(feature = "ssr"))]
|
||||
pub fn main() {
|
||||
// no client-side main function
|
||||
// unless we want this to work with e.g., Trunk for pure client-side testing
|
||||
// see lib.rs for hydration function instead
|
||||
}
|
||||
|
||||
3
src/models/mod.rs
Normal file
3
src/models/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
mod value;
|
||||
pub use value::Value;
|
||||
pub use value::OPTIONS;
|
||||
81
src/models/value.rs
Normal file
81
src/models/value.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
use chrono::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Option {
|
||||
pub value: &'static str,
|
||||
pub name: &'static str,
|
||||
service: &'static str,
|
||||
device: &'static str,
|
||||
r_type: &'static str,
|
||||
}
|
||||
|
||||
pub const OPTIONS: &[Option] = &[
|
||||
Option {
|
||||
value: "citerne",
|
||||
name: "Citerne",
|
||||
service: "home",
|
||||
device: "citerne",
|
||||
r_type: "height",
|
||||
},
|
||||
Option {
|
||||
value: "eau",
|
||||
name: "Eau",
|
||||
service: "home",
|
||||
device: "eau",
|
||||
r_type: "volume",
|
||||
},
|
||||
Option {
|
||||
value: "elec-hight",
|
||||
name: "Electricité heure pleine",
|
||||
service: "home",
|
||||
device: "elec",
|
||||
r_type: "pleine",
|
||||
},
|
||||
Option {
|
||||
value: "elec-low",
|
||||
name: "Electricité heure creuse",
|
||||
service: "home",
|
||||
device: "elec",
|
||||
r_type: "creuse",
|
||||
},
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Value {
|
||||
id: u16,
|
||||
service: String,
|
||||
capteur: String,
|
||||
type_donnee: String,
|
||||
donnee: String,
|
||||
}
|
||||
|
||||
impl Value {
|
||||
#[cfg(feature = "ssr")]
|
||||
pub async fn insert(
|
||||
device: String,
|
||||
value: String,
|
||||
) -> Result<sqlx::mysql::MySqlQueryResult, sqlx::Error> {
|
||||
let option = match find_option(&device) {
|
||||
Ok(option) => option,
|
||||
Err(err) => panic!("{}", err),
|
||||
};
|
||||
|
||||
sqlx::query!(
|
||||
"INSERT INTO data(service, device, type, data, date_data) VALUES (?, ?, ?, ?, NOW())",
|
||||
option.service,
|
||||
option.device,
|
||||
option.r_type,
|
||||
value,
|
||||
)
|
||||
.execute(crate::database::get_db())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
fn find_option(value: &str) -> Result<&Option, &str> {
|
||||
OPTIONS
|
||||
.iter()
|
||||
.find(|&option| option.value == value)
|
||||
.ok_or("No option found with the given value")
|
||||
}
|
||||
3
src/routes/mod.rs
Normal file
3
src/routes/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub use value::*;
|
||||
|
||||
mod value;
|
||||
51
src/routes/value.rs
Normal file
51
src/routes/value.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
use leptos::*;
|
||||
use leptos_meta::*;
|
||||
use leptos_router::*;
|
||||
|
||||
use crate::models::OPTIONS;
|
||||
|
||||
#[server(ValueAction, "/api")]
|
||||
pub async fn add_value(device: String, value: String) -> Result<(), ServerFnError> {
|
||||
crate::models::Value::insert(device, value)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|x| {
|
||||
let err = format!("Error while posting a comment: {x:?}");
|
||||
tracing::error!("{err}");
|
||||
ServerFnError::ServerError("Could not post a comment, try again later".into())
|
||||
})
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn FormValues() -> impl IntoView {
|
||||
let value_action = create_server_action::<ValueAction>();
|
||||
let result = value_action.version();
|
||||
let reset_value = create_rw_signal("");
|
||||
//let add_value = ServerAction::<AddValue>::new();
|
||||
//let value = add_value.value();
|
||||
//let has_error = move || value.with(|val| matches!(val, Some(Err(_))));
|
||||
|
||||
view! {
|
||||
<div class="my-0 mx-auto max-w-3xl text-center">
|
||||
<h2 class="p-6 text-4xl">"Formulaire"</h2>
|
||||
|
||||
<ActionForm action=value_action attr:class="border">
|
||||
<div>
|
||||
<label class="block">Capteur</label>
|
||||
<select name="device" class="dark:bg-slate-800 px-2 py-1">
|
||||
{OPTIONS.into_iter()
|
||||
.map(|option| view! { <option value={option.value}>{option.name}</option>})
|
||||
.collect::<Vec<_>>()}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block">Valeur</label>
|
||||
<input type="text" name="value" prop:value=move || reset_value.get() class="text-center dark:bg-slate-800 dark:text-white px-2 py-1" />
|
||||
</div>
|
||||
<div>
|
||||
<button type="submit" class="bg-slate-600 px-2 py-1 w-48 mt-3">Valider</button>
|
||||
</div>
|
||||
</ActionForm>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
49
src/setup.rs
Normal file
49
src/setup.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use leptos::*;
|
||||
use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
/// # Panics
|
||||
///
|
||||
/// Will panic if anything is badly setup from database, or web server
|
||||
pub async fn init_app(configuration_path: Option<&str>) {
|
||||
tracing_subscriber::fmt()
|
||||
.with_level(true)
|
||||
.with_max_level(tracing::Level::INFO)
|
||||
.init();
|
||||
// Init the pool into static
|
||||
crate::database::init_db()
|
||||
.await
|
||||
.expect("problem during initialization of the database");
|
||||
|
||||
// Get leptos configuration
|
||||
let conf = get_configuration(configuration_path).await.unwrap();
|
||||
let addr = conf.leptos_options.site_addr;
|
||||
// Generate the list of routes in your Leptos App
|
||||
let routes = generate_route_list(|| view! { <App/> });
|
||||
let leptos_options = conf.leptos_options;
|
||||
let serve_dir = tower_http::services::ServeDir::new(&leptos_options.site_root)
|
||||
.append_index_html_on_directories(false);
|
||||
|
||||
let app = axum::Router::new()
|
||||
.leptos_routes(&leptos_options, routes, || view! { <App/> })
|
||||
.fallback_service(serve_dir)
|
||||
.layer(
|
||||
tower_http::trace::TraceLayer::new_for_http()
|
||||
.make_span_with(
|
||||
tower_http::trace::DefaultMakeSpan::new().level(tracing::Level::INFO),
|
||||
)
|
||||
.on_request(tower_http::trace::DefaultOnRequest::new().level(tracing::Level::INFO))
|
||||
.on_response(
|
||||
tower_http::trace::DefaultOnResponse::new().level(tracing::Level::INFO),
|
||||
)
|
||||
.on_failure(
|
||||
tower_http::trace::DefaultOnFailure::new().level(tracing::Level::ERROR),
|
||||
),
|
||||
)
|
||||
//.layer(axum::middleware::from_fn(crate::auth::auth_middleware))
|
||||
.with_state(leptos_options);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
172
src/todo.rs
172
src/todo.rs
@@ -1,172 +0,0 @@
|
||||
use leptos::either::Either;
|
||||
use leptos::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
//use server_fn::ServerFnError;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
|
||||
pub struct Todo {
|
||||
id: u16,
|
||||
title: String,
|
||||
completed: bool,
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
pub mod ssr {
|
||||
// use http::{header::SET_COOKIE, HeaderMap, HeaderValue, StatusCode};
|
||||
use leptos::server_fn::ServerFnError;
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
|
||||
pub async fn db() -> Result<SqliteConnection, ServerFnError> {
|
||||
Ok(SqliteConnection::connect("sqlite:Todos.db").await?)
|
||||
}
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn get_todos() -> Result<Vec<Todo>, ServerFnError> {
|
||||
use self::ssr::*;
|
||||
|
||||
// this is just an example of how to access server context injected in the handlers
|
||||
let req_parts = use_context::<leptos_actix::Request>();
|
||||
|
||||
if let Some(req_parts) = req_parts {
|
||||
println!("Path = {:?}", req_parts.path());
|
||||
}
|
||||
|
||||
use futures::TryStreamExt;
|
||||
|
||||
let mut conn = db().await?;
|
||||
|
||||
let mut todos = Vec::new();
|
||||
let mut rows = sqlx::query_as::<_, Todo>("SELECT * FROM todos").fetch(&mut conn);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
todos.push(row);
|
||||
}
|
||||
|
||||
// Lines below show how to set status code and headers on the response
|
||||
// let resp = expect_context::<ResponseOptions>();
|
||||
// resp.set_status(StatusCode::IM_A_TEAPOT);
|
||||
// resp.insert_header(SET_COOKIE, HeaderValue::from_str("fizz=buzz").unwrap());
|
||||
|
||||
Ok(todos)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn add_todo(title: String) -> Result<(), ServerFnError> {
|
||||
use self::ssr::*;
|
||||
let mut conn = db().await?;
|
||||
|
||||
// fake API delay
|
||||
std::thread::sleep(std::time::Duration::from_millis(250));
|
||||
|
||||
match sqlx::query("INSERT INTO todos (title, completed) VALUES ($1, false)")
|
||||
.bind(title)
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
{
|
||||
Ok(_row) => Ok(()),
|
||||
Err(e) => Err(ServerFnError::ServerError(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
|
||||
use self::ssr::*;
|
||||
let mut conn = db().await?;
|
||||
|
||||
Ok(sqlx::query("DELETE FROM todos WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
.map(|_| ())?)
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn TodoApp() -> impl IntoView {
|
||||
view! {
|
||||
<header>
|
||||
<h1>"My Tasks"</h1>
|
||||
</header>
|
||||
<main>
|
||||
<Todos/>
|
||||
</main>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Todos() -> impl IntoView {
|
||||
let add_todo = ServerMultiAction::<AddTodo>::new();
|
||||
let submissions = add_todo.submissions();
|
||||
let delete_todo = ServerAction::<DeleteTodo>::new();
|
||||
|
||||
// list of todos is loaded from the server in reaction to changes
|
||||
let todos = Resource::new(
|
||||
move || {
|
||||
(
|
||||
delete_todo.version().get(),
|
||||
add_todo.version().get(),
|
||||
delete_todo.version().get(),
|
||||
)
|
||||
},
|
||||
move |_| get_todos(),
|
||||
);
|
||||
|
||||
let existing_todos = move || {
|
||||
Suspend::new(async move {
|
||||
todos.await.map(|todos| {
|
||||
if todos.is_empty() {
|
||||
Either::Left(view! { <p>"No tasks were found."</p> })
|
||||
} else {
|
||||
Either::Right(
|
||||
todos
|
||||
.iter()
|
||||
.map(move |todo| {
|
||||
let id = todo.id;
|
||||
view! {
|
||||
<li>
|
||||
{todo.title.clone()} <ActionForm action=delete_todo>
|
||||
<input type="hidden" name="id" value=id/>
|
||||
<input type="submit" value="X"/>
|
||||
</ActionForm>
|
||||
</li>
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
view! {
|
||||
<MultiActionForm action=add_todo>
|
||||
<label>"Add a Todo" <input type="text" name="title"/></label>
|
||||
<input type="submit" value="Add"/>
|
||||
</MultiActionForm>
|
||||
<div>
|
||||
<Transition fallback=move || view! { <p>"Loading..."</p> }>
|
||||
// TODO: ErrorBoundary here seems to break Suspense in Actix
|
||||
// <ErrorBoundary fallback=|errors| view! { <p>"Error: " {move || format!("{:?}", errors.get())}</p> }>
|
||||
<ul>
|
||||
{existing_todos}
|
||||
{move || {
|
||||
submissions
|
||||
.get()
|
||||
.into_iter()
|
||||
.filter(|submission| submission.pending().get())
|
||||
.map(|submission| {
|
||||
view! {
|
||||
<li class="pending">
|
||||
{move || submission.input().get().map(|data| data.title)}
|
||||
</li>
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}}
|
||||
|
||||
</ul>
|
||||
// </ErrorBoundary>
|
||||
</Transition>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
118
src/values.rs
118
src/values.rs
@@ -1,118 +0,0 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos_meta::*;
|
||||
use leptos_router::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub struct Option {
|
||||
value: &'static str,
|
||||
name: &'static str,
|
||||
topic: &'static str,
|
||||
}
|
||||
|
||||
pub const OPTIONS: &[Option] = &[
|
||||
Option {
|
||||
value: "citerne",
|
||||
name: "Citerne",
|
||||
topic: "home/citerne/height",
|
||||
},
|
||||
Option {
|
||||
value: "eau",
|
||||
name: "Eau",
|
||||
topic: "home/eau/volume",
|
||||
},
|
||||
Option {
|
||||
value: "elec-hight",
|
||||
name: "Electricité heure pleine",
|
||||
topic: "home/elec-hight/pleine",
|
||||
},
|
||||
Option {
|
||||
value: "elec-low",
|
||||
name: "Electricité heure creuse",
|
||||
topic: "home/elec-low/creuse",
|
||||
},
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Value {
|
||||
id: u16,
|
||||
service: String,
|
||||
capteur: String,
|
||||
type_donnee: String,
|
||||
donnee: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
|
||||
struct HeftyData {
|
||||
capteur: String,
|
||||
value: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
pub mod ssr {
|
||||
// use http::{header::SET_COOKIE, HeaderMap, HeaderValue, StatusCode};
|
||||
use leptos::server_fn::ServerFnError;
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
|
||||
pub async fn db() -> Result<SqliteConnection, ServerFnError> {
|
||||
Ok(SqliteConnection::connect("sqlite:Todos.db").await?)
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Form() -> impl IntoView {
|
||||
view! {
|
||||
<div class="my-0 mx-auto max-w-3xl text-center">
|
||||
<h2 class="p-6 text-4xl">"Formulaire"</h2>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn FormValues() -> impl IntoView {
|
||||
let add_value = ServerAction::<AddValue>::new();
|
||||
let value = add_value.value();
|
||||
let has_error = move || value.with(|val| matches!(val, Some(Err(_))));
|
||||
|
||||
view! {
|
||||
<div class="my-0 mx-auto max-w-3xl text-center">
|
||||
<h2 class="p-6 text-4xl">"Formulaire"</h2>
|
||||
|
||||
<ActionForm action=add_value attr:class="border">
|
||||
<div>
|
||||
<label class="block">Capteur</label>
|
||||
<select name="hefty_arg[capteur]">
|
||||
{OPTIONS.into_iter()
|
||||
.map(|option| view! { <option value={option.value}>{option.name}</option>})
|
||||
.collect::<Vec<_>>()}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block">Valeur</label>
|
||||
<input type="text" name="hefty_arg[value]" />
|
||||
</div>
|
||||
<div>
|
||||
<button type="submit">Valider</button>
|
||||
</div>
|
||||
</ActionForm>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[server(AddValue, "/api/add-value")]
|
||||
pub async fn add_value(hefty_arg: HeftyData) -> Result<(), ServerFnError> {
|
||||
use self::ssr::*;
|
||||
let mut conn = db().await?;
|
||||
|
||||
dbg!(&hefty_arg);
|
||||
|
||||
match sqlx::query("INSERT INTO donnees (service, donnee) VALUES ($1, $2)")
|
||||
.bind(hefty_arg.capteur)
|
||||
.bind(hefty_arg.value)
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(ServerFnError::ServerError(e.to_string())),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user