Add frontend tests and other stuff

This commit is contained in:
Greg Burri 2022-12-07 00:16:34 +01:00
parent d28e765e39
commit 642dd8a80c
26 changed files with 730 additions and 85 deletions

5
.gitignore vendored
View file

@ -8,3 +8,8 @@ backend/static/style.css
backend/file.db backend/file.db
*.sqlite *.sqlite
conf.ron conf.ron
*.wasm
node_modules
pkg
package-lock.json

131
Cargo.lock generated
View file

@ -169,7 +169,7 @@ dependencies = [
"ahash", "ahash",
"bytes", "bytes",
"bytestring", "bytestring",
"cfg-if", "cfg-if 1.0.0",
"cookie", "cookie",
"derive_more", "derive_more",
"encoding_rs", "encoding_rs",
@ -429,6 +429,12 @@ dependencies = [
"jobserver", "jobserver",
] ]
[[package]]
name = "cfg-if"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
version = "1.0.0" version = "1.0.0"
@ -523,6 +529,16 @@ dependencies = [
"xdg", "xdg",
] ]
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
dependencies = [
"cfg-if 1.0.0",
"wasm-bindgen",
]
[[package]] [[package]]
name = "convert_case" name = "convert_case"
version = "0.4.0" version = "0.4.0"
@ -561,7 +577,7 @@ version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"
dependencies = [ dependencies = [
"cfg-if", "cfg-if 1.0.0",
] ]
[[package]] [[package]]
@ -576,9 +592,9 @@ dependencies = [
[[package]] [[package]]
name = "cxx" name = "cxx"
version = "1.0.82" version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4a41a86530d0fe7f5d9ea779916b7cadd2d4f9add748b99c2c029cbbdfaf453" checksum = "bdf07d07d6531bfcdbe9b8b739b104610c6508dcc4d63b410585faf338241daf"
dependencies = [ dependencies = [
"cc", "cc",
"cxxbridge-flags", "cxxbridge-flags",
@ -588,9 +604,9 @@ dependencies = [
[[package]] [[package]]
name = "cxx-build" name = "cxx-build"
version = "1.0.82" version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06416d667ff3e3ad2df1cd8cd8afae5da26cf9cec4d0825040f88b5ca659a2f0" checksum = "d2eb5b96ecdc99f72657332953d4d9c50135af1bac34277801cc3937906ebd39"
dependencies = [ dependencies = [
"cc", "cc",
"codespan-reporting", "codespan-reporting",
@ -603,15 +619,15 @@ dependencies = [
[[package]] [[package]]
name = "cxxbridge-flags" name = "cxxbridge-flags"
version = "1.0.82" version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "820a9a2af1669deeef27cb271f476ffd196a2c4b6731336011e0ba63e2c7cf71" checksum = "ac040a39517fd1674e0f32177648334b0f4074625b5588a64519804ba0553b12"
[[package]] [[package]]
name = "cxxbridge-macro" name = "cxxbridge-macro"
version = "1.0.82" version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a08a6e2fcc370a089ad3b4aaf54db3b1b4cee38ddabce5896b33eb693275f470" checksum = "1362b0ddcfc4eb0a1f57b68bd77dd99f0e826958a96abd0ae9bd092e114ffed6"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -690,7 +706,7 @@ version = "0.8.31"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b" checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b"
dependencies = [ dependencies = [
"cfg-if", "cfg-if 1.0.0",
] ]
[[package]] [[package]]
@ -779,6 +795,17 @@ dependencies = [
"percent-encoding", "percent-encoding",
] ]
[[package]]
name = "frontend"
version = "0.1.0"
dependencies = [
"common",
"console_error_panic_hook",
"wasm-bindgen",
"web-sys",
"wee_alloc",
]
[[package]] [[package]]
name = "futures" name = "futures"
version = "0.3.25" version = "0.3.25"
@ -884,7 +911,7 @@ version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31"
dependencies = [ dependencies = [
"cfg-if", "cfg-if 1.0.0",
"libc", "libc",
"wasi 0.11.0+wasi-snapshot-preview1", "wasi 0.11.0+wasi-snapshot-preview1",
] ]
@ -1063,7 +1090,7 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [ dependencies = [
"cfg-if", "cfg-if 1.0.0",
] ]
[[package]] [[package]]
@ -1159,9 +1186,9 @@ dependencies = [
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.137" version = "0.2.138"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8"
[[package]] [[package]]
name = "libsqlite3-sys" name = "libsqlite3-sys"
@ -1223,7 +1250,7 @@ version = "0.4.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
dependencies = [ dependencies = [
"cfg-if", "cfg-if 1.0.0",
] ]
[[package]] [[package]]
@ -1244,6 +1271,12 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "memory_units"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3"
[[package]] [[package]]
name = "mime" name = "mime"
version = "0.3.16" version = "0.3.16"
@ -1354,7 +1387,7 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ff9f3fef3968a3ec5945535ed654cb38ff72d7495a25619e2247fb15a2ed9ba" checksum = "7ff9f3fef3968a3ec5945535ed654cb38ff72d7495a25619e2247fb15a2ed9ba"
dependencies = [ dependencies = [
"cfg-if", "cfg-if 1.0.0",
"libc", "libc",
"redox_syscall", "redox_syscall",
"smallvec", "smallvec",
@ -1386,9 +1419,9 @@ checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
[[package]] [[package]]
name = "pest" name = "pest"
version = "2.5.0" version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f400b0f7905bf702f9f3dc3df5a121b16c54e9e8012c082905fdf09a931861a" checksum = "cc8bed3549e0f9b0a2a78bf7c0018237a2cdf085eecbbc048e52612438e4e9d0"
dependencies = [ dependencies = [
"thiserror", "thiserror",
"ucd-trie", "ucd-trie",
@ -1396,9 +1429,9 @@ dependencies = [
[[package]] [[package]]
name = "pest_derive" name = "pest_derive"
version = "2.5.0" version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "423c2ba011d6e27b02b482a3707c773d19aec65cc024637aec44e19652e66f63" checksum = "cdc078600d06ff90d4ed238f0119d84ab5d43dbaad278b0e33a8820293b32344"
dependencies = [ dependencies = [
"pest", "pest",
"pest_generator", "pest_generator",
@ -1406,9 +1439,9 @@ dependencies = [
[[package]] [[package]]
name = "pest_generator" name = "pest_generator"
version = "2.5.0" version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e64e6c2c85031c02fdbd9e5c72845445ca0a724d419aa0bc068ac620c9935c1" checksum = "28a1af60b1c4148bb269006a750cff8e2ea36aff34d2d96cf7be0b14d1bed23c"
dependencies = [ dependencies = [
"pest", "pest",
"pest_meta", "pest_meta",
@ -1419,9 +1452,9 @@ dependencies = [
[[package]] [[package]]
name = "pest_meta" name = "pest_meta"
version = "2.5.0" version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57959b91f0a133f89a68be874a5c88ed689c19cd729ecdb5d762ebf16c64d662" checksum = "fec8605d59fc2ae0c6c1aefc0c7c7a9769732017c0ce07f7a9cfffa7b4404f20"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"pest", "pest",
@ -1496,9 +1529,9 @@ dependencies = [
[[package]] [[package]]
name = "quoted_printable" name = "quoted_printable"
version = "0.4.5" version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fee2dce59f7a43418e3382c766554c614e06a552d53a8f07ef499ea4b332c0f" checksum = "20f14e071918cbeefc5edc986a7aa92c425dae244e003a35e1cdddb5ca39b5cb"
[[package]] [[package]]
name = "r2d2" name = "r2d2"
@ -1667,9 +1700,9 @@ dependencies = [
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "0.36.4" version = "0.36.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb93e85278e08bb5788653183213d3a60fc242b10cb9be96586f5a73dcb67c23" checksum = "a3807b5d10909833d3e9acd1eb5fb988f79376ff10fce42937de71a449c4c588"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"errno", "errno",
@ -1745,18 +1778,18 @@ checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.148" version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e53f64bb4ba0191d6d0676e1b141ca55047d83b74f5607e6d8eb88126c52c2dc" checksum = "256b9932320c590e707b94576e3cc1f7c9024d0ee6612dfbcf1cb106cbe8e055"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.148" version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a55492425aa53521babf6137309e7d34c20bbfbbfcfe2c7f3a047fd1f6b92c0c" checksum = "b4eae9b04cbffdfd550eb462ed33bc6a1b68c935127d008b27444d08380f94e4"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -1792,7 +1825,7 @@ version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3"
dependencies = [ dependencies = [
"cfg-if", "cfg-if 1.0.0",
"cpufeatures", "cpufeatures",
"digest", "digest",
] ]
@ -1857,9 +1890,9 @@ checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601"
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.104" version = "1.0.105"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae548ec36cf198c0ef7710d3c230987c2d6d7bd98ad6edc0274462724c585ce" checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -1950,9 +1983,9 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.22.0" version = "1.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d76ce4a75fb488c605c54bf610f221cea8b0dafb53333c1a67e8ee199dcd2ae3" checksum = "eab6d665857cc6ca78d6e80303a02cea7a7851e85dfbd77cbdc09bd129f1ef46"
dependencies = [ dependencies = [
"autocfg", "autocfg",
"bytes", "bytes",
@ -1963,7 +1996,7 @@ dependencies = [
"pin-project-lite", "pin-project-lite",
"signal-hook-registry", "signal-hook-registry",
"socket2", "socket2",
"winapi", "windows-sys",
] ]
[[package]] [[package]]
@ -1995,7 +2028,7 @@ version = "0.1.37"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8"
dependencies = [ dependencies = [
"cfg-if", "cfg-if 1.0.0",
"log", "log",
"pin-project-lite", "pin-project-lite",
"tracing-core", "tracing-core",
@ -2028,9 +2061,9 @@ checksum = "a9b2228007eba4120145f785df0f6c92ea538f5a3635a612ecf4e334c8c1446d"
[[package]] [[package]]
name = "typenum" name = "typenum"
version = "1.15.0" version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
[[package]] [[package]]
name = "ucd-trie" name = "ucd-trie"
@ -2133,7 +2166,7 @@ version = "0.2.83"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268"
dependencies = [ dependencies = [
"cfg-if", "cfg-if 1.0.0",
"wasm-bindgen-macro", "wasm-bindgen-macro",
] ]
@ -2210,6 +2243,18 @@ dependencies = [
"webpki", "webpki",
] ]
[[package]]
name = "wee_alloc"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e"
dependencies = [
"cfg-if 0.1.10",
"libc",
"memory_units",
"winapi",
]
[[package]] [[package]]
name = "winapi" name = "winapi"
version = "0.3.9" version = "0.3.9"

View file

@ -2,6 +2,7 @@
members = [ members = [
"backend", "backend",
"frontend",
"common", "common",
] ]

View file

@ -1,6 +1,10 @@
# Use cases # Use cases
## Create a recipe ## Create a recipe
To create a recipe the user must have an account.
* The user
(A group is automatically created) (A group is automatically created)
## Create a groupe ## Create a groupe
@ -21,21 +25,29 @@
The toolchain for Raspberry Pi 64 bits is available here: https://gnutoolchains.com/raspberry64/ The toolchain for Raspberry Pi 64 bits is available here: https://gnutoolchains.com/raspberry64/
## How to install service on RPI Zero ## How to install service on RPI Zero
1. Copy doc/recipes.service to /lib/systemd/system 1. Copy doc/recipes.service to /lib/systemd/system
2. Enabled it: #> systemctl enable recipes 2. Enabled it: #> systemctl enable recipes
## Backend
Autoreload: https://actix.rs/docs/autoreload/
### Frontend
## WebAssembly
'frontend' project needs some tools to generate the WebAssembly stuff. Everything is explained here: https://rustwasm.github.io/wasm-bindgen/examples/hello-world.html
To compile run 'wasm-pack build' in 'frontend' directory
To launch node run 'npm run start' in 'frontend/www' directory
## Useful URLs ## Useful URLs
* Rust patterns : https://github.com/rust-unofficial/patterns/tree/master/patterns * Rust patterns : https://github.com/rust-unofficial/patterns/tree/master/patterns
* Rusqlite (SQLite) : https://docs.rs/rusqlite/0.20.0/rusqlite/ * Rusqlite (SQLite) : https://docs.rs/rusqlite/0.20.0/rusqlite/
* Node install: https://nodejs.org/en/download/
## How to develop
Autoreload: https://actix.rs/docs/autoreload/

View file

@ -1,8 +1,10 @@
* Change all id to i64
* Try using WASM for all the client logic (test on signup page) * Try using WASM for all the client logic (test on signup page)
* Describe the use cases. * Describe the use cases.
* Define the UI (mockups). * Define the UI (mockups).
* Two CSS: one for desktop and one for mobile * Two CSS: one for desktop and one for mobile
* Define the logic behind each page and action. * Define the logic behind each page and action.
* Add support to language into db model.
[ok] Check cookie lifetime -> Session by default [ok] Check cookie lifetime -> Session by default
[ok] Asynchonous email sending and database requests [ok] Asynchonous email sending and database requests

View file

@ -1,7 +1,7 @@
INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token]) INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])
VALUES ( VALUES (
1, 1,
'paul@test.org', 'paul@atreides.com',
'paul', 'paul',
'$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY', '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',
0, 0,

View file

@ -42,10 +42,21 @@ CREATE TABLE [Recipe] (
[estimate_time] INTEGER, [estimate_time] INTEGER,
[description] TEXT, [description] TEXT,
[servings] INTEGER DEFAULT 4, [servings] INTEGER DEFAULT 4,
[is_published] INTEGER NOT NULL DEFAULT FALSE,
FOREIGN KEY([user_id]) REFERENCES [User]([id]) ON DELETE SET NULL FOREIGN KEY([user_id]) REFERENCES [User]([id]) ON DELETE SET NULL
); );
CREATE TABLE [Image] (
[Id] INTEGER PRIMARY KEY,
[recipe_id] INTEGER NOT NULL,
[name] TEXT,
[description] TEXT,
[image] BLOB,
FOREIGN KEY([recipe_id]) REFERENCES [Recipe]([id]) ON DELETE CASCADE
);
CREATE TABLE [RecipeTag] ( CREATE TABLE [RecipeTag] (
[id] INTEGER PRIMARY KEY, [id] INTEGER PRIMARY KEY,

View file

@ -49,17 +49,17 @@ fn combine_errors<T>(error: std::result::Result<std::result::Result<T, DBAsyncEr
type Result<T> = std::result::Result<T, DBAsyncError>; type Result<T> = std::result::Result<T, DBAsyncError>;
impl Connection { impl Connection {
pub async fn get_all_recipe_titles_async(&self) -> Result<Vec<(i32, String)>> { pub async fn get_all_recipe_titles_async(&self) -> Result<Vec<(i64, String)>> {
let self_copy = self.clone(); let self_copy = self.clone();
web::block(move || { self_copy.get_all_recipe_titles().unwrap_or_default() }).await.map_err(DBAsyncError::from) web::block(move || { self_copy.get_all_recipe_titles().unwrap_or_default() }).await.map_err(DBAsyncError::from)
} }
pub async fn get_recipe_async(&self, id: i32) -> Result<model::Recipe> { pub async fn get_recipe_async(&self, id: i64) -> Result<model::Recipe> {
let self_copy = self.clone(); let self_copy = self.clone();
combine_errors(web::block(move || { self_copy.get_recipe(id).map_err(DBAsyncError::from) }).await) combine_errors(web::block(move || { self_copy.get_recipe(id).map_err(DBAsyncError::from) }).await)
} }
pub async fn load_user_async(&self, user_id: i32) -> Result<User> { pub async fn load_user_async(&self, user_id: i64) -> Result<User> {
let self_copy = self.clone(); let self_copy = self.clone();
combine_errors(web::block(move || { self_copy.load_user(user_id).map_err(DBAsyncError::from) }).await) combine_errors(web::block(move || { self_copy.load_user(user_id).map_err(DBAsyncError::from) }).await)
} }
@ -101,4 +101,15 @@ impl Connection {
let token_copy = token.to_string(); let token_copy = token.to_string();
combine_errors(web::block(move || { self_copy.sign_out(&token_copy).map_err(DBAsyncError::from) }).await) combine_errors(web::block(move || { self_copy.sign_out(&token_copy).map_err(DBAsyncError::from) }).await)
} }
pub async fn create_recipe_async(&self, user_id: i64) -> Result<i64> {
let self_copy = self.clone();
combine_errors(web::block(move || { self_copy.create_recipe(user_id).map_err(DBAsyncError::from) }).await)
}
pub async fn set_recipe_title_async(&self, recipe_id: i64, title: &str) -> Result<()> {
let self_copy = self.clone();
let title_copy = title.to_string();
combine_errors(web::block(move || { self_copy.set_recipe_title(recipe_id, &title_copy).map_err(DBAsyncError::from) }).await)
}
} }

View file

@ -60,7 +60,7 @@ pub enum SignUpResult {
pub enum ValidationResult { pub enum ValidationResult {
UnknownUser, UnknownUser,
ValidationExpired, ValidationExpired,
Ok(String, i32), // Returns token and user id. Ok(String, i64), // Returns token and user id.
} }
#[derive(Debug)] #[derive(Debug)]
@ -68,18 +68,17 @@ pub enum SignInResult {
UserNotFound, UserNotFound,
WrongPassword, WrongPassword,
AccountNotValidated, AccountNotValidated,
Ok(String, i32), // Returns token and user id. Ok(String, i64), // Returns token and user id.
} }
#[derive(Debug)] #[derive(Debug)]
pub enum AuthenticationResult { pub enum AuthenticationResult {
NotValidToken, NotValidToken,
Ok(i32), // Returns user id. Ok(i64), // Returns user id.
} }
#[derive(Clone)] #[derive(Clone)]
pub struct Connection { pub struct Connection {
//con: rusqlite::Connection
pool: Pool<SqliteConnectionManager> pool: Pool<SqliteConnectionManager>
} }
@ -106,13 +105,13 @@ impl Connection {
fn create_connection(manager: SqliteConnectionManager) -> Result<Connection> { fn create_connection(manager: SqliteConnectionManager) -> Result<Connection> {
let pool = r2d2::Pool::new(manager).unwrap(); let pool = r2d2::Pool::new(manager).unwrap();
let connection = Connection { pool }; let connection = Connection { pool };
connection.create_or_update()?; connection.create_or_update_db()?;
Ok(connection) Ok(connection)
} }
/// Called after the connection has been established for creating or updating the database. /// Called after the connection has been established for creating or updating the database.
/// The 'Version' table tracks the current state of the database. /// The 'Version' table tracks the current state of the database.
fn create_or_update(&self) -> Result<()> { fn create_or_update_db(&self) -> Result<()> {
// Check the Database version. // Check the Database version.
let mut con = self.pool.get()?; let mut con = self.pool.get()?;
let tx = con.transaction()?; let tx = con.transaction()?;
@ -174,12 +173,12 @@ impl Connection {
} }
} }
pub fn get_all_recipe_titles(&self) -> Result<Vec<(i32, String)>> { pub fn get_all_recipe_titles(&self) -> Result<Vec<(i64, String)>> {
let con = self.pool.get()?; let con = self.pool.get()?;
let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?; let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;
let titles: std::result::Result<Vec<(i32, String)>, rusqlite::Error> = let titles: std::result::Result<Vec<(i64, String)>, rusqlite::Error> =
stmt.query_map([], |row| { stmt.query_map([], |row| {
Ok((row.get("id")?, row.get("title")?)) Ok((row.get("id")?, row.get("title")?))
})?.collect(); })?.collect();
@ -198,7 +197,7 @@ impl Connection {
Ok(recipes) Ok(recipes)
} */ } */
pub fn get_recipe(&self, id: i32) -> Result<model::Recipe> { pub fn get_recipe(&self, id: i64) -> Result<model::Recipe> {
let con = self.pool.get()?; let con = self.pool.get()?;
con.query_row("SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1", [id], |row| { con.query_row("SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1", [id], |row| {
Ok(model::Recipe::new(row.get("id")?, row.get("title")?, row.get("description")?)) Ok(model::Recipe::new(row.get("id")?, row.get("title")?, row.get("description")?))
@ -216,7 +215,7 @@ impl Connection {
}).map_err(DBError::from) }).map_err(DBError::from)
} }
pub fn load_user(&self, user_id: i32) -> Result<User> { pub fn load_user(&self, user_id: i64) -> Result<User> {
let con = self.pool.get()?; let con = self.pool.get()?;
con.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id], |r| { con.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id], |r| {
Ok(User { Ok(User {
@ -234,7 +233,7 @@ impl Connection {
let tx = con.transaction()?; let tx = con.transaction()?;
let token = let token =
match tx.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| { match tx.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {
Ok((r.get::<&str, i32>("id")?, r.get::<&str, Option<String>>("validation_token")?)) Ok((r.get::<&str, i64>("id")?, r.get::<&str, Option<String>>("validation_token")?))
}).optional()? { }).optional()? {
Some((id, validation_token)) => { Some((id, validation_token)) => {
if validation_token.is_none() { if validation_token.is_none() {
@ -261,7 +260,7 @@ impl Connection {
let tx = con.transaction()?; let tx = con.transaction()?;
let user_id = let user_id =
match tx.query_row("SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", [token], |r| { match tx.query_row("SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", [token], |r| {
Ok((r.get::<&str, i32>("id")?, r.get::<&str, DateTime<Utc>>("creation_datetime")?)) Ok((r.get::<&str, i64>("id")?, r.get::<&str, DateTime<Utc>>("creation_datetime")?))
}).optional()? { }).optional()? {
Some((id, creation_datetime)) => { Some((id, creation_datetime)) => {
if Utc::now() - creation_datetime > validation_time { if Utc::now() - creation_datetime > validation_time {
@ -283,7 +282,7 @@ impl Connection {
let mut con = self.pool.get()?; let mut con = self.pool.get()?;
let tx = con.transaction()?; let tx = con.transaction()?;
match tx.query_row("SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| { match tx.query_row("SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {
Ok((r.get::<&str, i32>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option<String>>("validation_token")?)) Ok((r.get::<&str, i64>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option<String>>("validation_token")?))
}).optional()? { }).optional()? {
Some((id, stored_password, validation_token)) => { Some((id, stored_password, validation_token)) => {
if validation_token.is_some() { if validation_token.is_some() {
@ -306,7 +305,7 @@ impl Connection {
let mut con = self.pool.get()?; let mut con = self.pool.get()?;
let tx = con.transaction()?; let tx = con.transaction()?;
match tx.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| { match tx.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| {
Ok((r.get::<&str, i32>("id")?, r.get::<&str, i32>("user_id")?)) Ok((r.get::<&str, i64>("id")?, r.get::<&str, i64>("user_id")?))
}).optional()? { }).optional()? {
Some((login_id, user_id)) => { Some((login_id, user_id)) => {
tx.execute("UPDATE [UserLoginToken] SET [last_login_datetime] = ?2, [ip] = ?3, [user_agent] = ?4 WHERE [id] = ?1", params![login_id, Utc::now(), ip, user_agent])?; tx.execute("UPDATE [UserLoginToken] SET [last_login_datetime] = ?2, [ip] = ?3, [user_agent] = ?4 WHERE [id] = ?1", params![login_id, Utc::now(), ip, user_agent])?;
@ -322,7 +321,7 @@ impl Connection {
let mut con = self.pool.get()?; let mut con = self.pool.get()?;
let tx = con.transaction()?; let tx = con.transaction()?;
match tx.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| { match tx.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| {
Ok(r.get::<&str, i32>("id")?) Ok(r.get::<&str, i64>("id")?)
}).optional()? { }).optional()? {
Some(login_id) => { Some(login_id) => {
tx.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params![login_id])?; tx.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params![login_id])?;
@ -333,6 +332,33 @@ impl Connection {
Ok(()) Ok(())
} }
pub fn create_recipe(&self, user_id: i64) -> Result<i64> {
let con = self.pool.get()?;
// Verify if an empty recipe already exists. Returns its id if one exists.
match con.query_row(
"SELECT [Recipe].[id] FROM [Recipe]
INNER JOIN [Image] ON [Image].[recipe_id] = [Recipe].[id]
INNER JOIN [Group] ON [Group].[recipe_id] = [Recipe].[id]
WHERE [Recipe].[user_id] = ?1 AND [Recipe].[estimate_time] = NULL AND [Recipe].[description] = NULL",
[user_id],
|r| {
Ok(r.get::<&str, i64>("id")?)
}
).optional()? {
Some(recipe_id) => Ok(recipe_id),
None => {
con.execute("INSERT INTO [Recipe] ([user_id], [title]) VALUES (?1, '')", [user_id])?;
Ok(con.last_insert_rowid())
},
}
}
pub fn set_recipe_title(&self, recipe_id: i64, title: &str) -> Result<()> {
let con = self.pool.get()?;
con.execute("UPDATE [Recipe] SET [title] = ?2 WHERE [id] = ?1", params![recipe_id, title]).map(|_n| ()).map_err(DBError::from)
}
/// Execute a given SQL file. /// Execute a given SQL file.
pub fn execute_file<P: AsRef<Path> + fmt::Display>(&self, file: P) -> Result<()> { pub fn execute_file<P: AsRef<Path> + fmt::Display>(&self, file: P) -> Result<()> {
let con = self.pool.get()?; let con = self.pool.get()?;
@ -348,7 +374,7 @@ impl Connection {
} }
// Return the token. // Return the token.
fn create_login_token(tx: &rusqlite::Transaction, user_id: i32, ip: &str, user_agent: &str) -> Result<String> { fn create_login_token(tx: &rusqlite::Transaction, user_id: i64, ip: &str, user_agent: &str) -> Result<String> {
let token = generate_token(); let token = generate_token();
tx.execute("INSERT INTO [UserLoginToken] ([user_id], [last_login_datetime], [token], [ip], [user_agent]) VALUES (?1, ?2, ?3, ?4, ?5)", params![user_id, Utc::now(), token, ip, user_agent])?; tx.execute("INSERT INTO [UserLoginToken] ([user_id], [last_login_datetime], [token], [ip], [user_agent]) VALUES (?1, ?2, ?3, ?4, ?5)", params![user_id, Utc::now(), token, ip, user_agent])?;
Ok(token) Ok(token)
@ -369,6 +395,7 @@ fn generate_token() -> String {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use rusqlite::{Error, ErrorCode, ffi, types::Value};
#[test] #[test]
fn sign_up() -> Result<()> { fn sign_up() -> Result<()> {
@ -603,4 +630,37 @@ mod tests {
Ok(()) Ok(())
} }
#[test]
fn create_a_new_recipe_then_update_its_title() -> Result<()> {
let connection = Connection::new_in_memory()?;
connection.execute_sql(
"INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token]) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
1,
"paul@atreides.com",
"paul",
"$argon2id$v=19$m=4096,t=3,p=1$G4fjepS05MkRbTqEImUdYg$GGziE8uVQe1L1oFHk37lBno10g4VISnVqynSkLCH3Lc",
"2022-11-29 22:05:04.121407300+00:00",
Value::Null,
]
)?;
match connection.create_recipe(2) {
Err(DBError::SqliteError(Error::SqliteFailure(ffi::Error { code: ErrorCode::ConstraintViolation, extended_code: _ }, Some(_)))) => (), // Nominal case.
other => panic!("Creating a recipe with an inexistant user must fail: {:?}", other),
}
let recipe_id = connection.create_recipe(1)?;
assert_eq!(recipe_id, 1);
connection.set_recipe_title(recipe_id, "Crêpe")?;
let recipe = connection.get_recipe(recipe_id)?;
assert_eq!(recipe.title, "Crêpe".to_string());
Ok(())
}
} }

View file

@ -1,5 +1,5 @@
pub struct Recipe { pub struct Recipe {
pub id: i32, pub id: i64,
pub title: String, pub title: String,
pub description: Option<String>, pub description: Option<String>,
pub estimate_time: Option<i32>, // [min]. pub estimate_time: Option<i32>, // [min].
@ -10,7 +10,7 @@ pub struct Recipe {
} }
impl Recipe { impl Recipe {
pub fn new(id: i32, title: String, description: Option<String>) -> Recipe { pub fn new(id: i64, title: String, description: Option<String>) -> Recipe {
Recipe { Recipe {
id, id,
title, title,

View file

@ -14,6 +14,8 @@ use crate::user::User;
use crate::model; use crate::model;
use crate::data::{db, asynchronous}; use crate::data::{db, asynchronous};
mod api;
///// UTILS ///// ///// UTILS /////
fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) { fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) {
@ -119,8 +121,8 @@ impl actix_web::error::ResponseError for ServiceError {
#[template(path = "home.html")] #[template(path = "home.html")]
struct HomeTemplate { struct HomeTemplate {
user: Option<User>, user: Option<User>,
recipes: Vec<(i32, String)>, recipes: Vec<(i64, String)>,
current_recipe_id: Option<i32>, current_recipe_id: Option<i64>,
} }
#[get("/")] #[get("/")]
@ -137,13 +139,13 @@ pub async fn home_page(req: HttpRequest, connection: web::Data<db::Connection>)
#[template(path = "view_recipe.html")] #[template(path = "view_recipe.html")]
struct ViewRecipeTemplate { struct ViewRecipeTemplate {
user: Option<User>, user: Option<User>,
recipes: Vec<(i32, String)>, recipes: Vec<(i64, String)>,
current_recipe_id: Option<i32>, current_recipe_id: Option<i64>,
current_recipe: model::Recipe, current_recipe: model::Recipe,
} }
#[get("/recipe/view/{id}")] #[get("/recipe/view/{id}")]
pub async fn view_recipe(req: HttpRequest, path: web::Path<(i32,)>, connection: web::Data<db::Connection>) -> Result<HttpResponse> { pub async fn view_recipe(req: HttpRequest, path: web::Path<(i64,)>, connection: web::Data<db::Connection>) -> Result<HttpResponse> {
let (id,)= path.into_inner(); let (id,)= path.into_inner();
let user = get_current_user(&req, connection.clone()).await; let user = get_current_user(&req, connection.clone()).await;
let recipes = connection.get_all_recipe_titles_async().await?; let recipes = connection.get_all_recipe_titles_async().await?;
@ -255,10 +257,10 @@ pub async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, con
Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => { Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => {
let url = { let url = {
let host = req.headers().get(header::HOST).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default(); let host = req.headers().get(header::HOST).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default();
let port: Option<i32> = 'p: { let port: Option<u16> = 'p: {
let split_port: Vec<&str> = host.split(':').collect(); let split_port: Vec<&str> = host.split(':').collect();
if split_port.len() == 2 { if split_port.len() == 2 {
if let Ok(p) = split_port[1].parse::<i32>() { if let Ok(p) = split_port[1].parse::<u16>() {
break 'p Some(p) break 'p Some(p)
} }
} }

View file

@ -0,0 +1,27 @@
use actix_web::{http::{header, header::ContentType, StatusCode}, get, post, put, web, Responder, HttpRequest, HttpResponse, cookie::Cookie};
use chrono::Duration;
use serde::Deserialize;
use log::{debug, error, log_enabled, info, Level};
use super::Result;
use crate::utils;
use crate::consts;
use crate::config::Config;
use crate::user::User;
use crate::model;
use crate::data::{db, asynchronous};
#[put("/ron-api/set-title")]
pub async fn set_title(req: HttpRequest, connection: web::Data<db::Connection>) -> Result<HttpResponse> {
//req.app_config()
let id = 1;
let title = "XYZ".to_string();
//let recipes = connection.set_recipe_title_async(id, title).await?;
Ok(
HttpResponse::Ok()
.content_type("application/ron")
.body("DATA")
)
}

294
backend/static/frontend.js Normal file
View file

@ -0,0 +1,294 @@
let wasm;
const cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
let cachedUint8Memory0 = new Uint8Array();
function getUint8Memory0() {
if (cachedUint8Memory0.byteLength === 0) {
cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8Memory0;
}
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
const heap = new Array(32).fill(undefined);
heap.push(undefined, null, true, false);
let heap_next = heap.length;
function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1);
const idx = heap_next;
heap_next = heap[idx];
heap[idx] = obj;
return idx;
}
function getObject(idx) { return heap[idx]; }
function dropObject(idx) {
if (idx < 36) return;
heap[idx] = heap_next;
heap_next = idx;
}
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
let WASM_VECTOR_LEN = 0;
const cachedTextEncoder = new TextEncoder('utf-8');
const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
? function (arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
}
: function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
});
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length);
getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len);
const mem = getUint8Memory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3);
const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
/**
* @param {string} name
*/
export function greet(name) {
const ptr0 = passStringToWasm0(name, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
const len0 = WASM_VECTOR_LEN;
wasm.greet(ptr0, len0);
}
/**
*/
export function main() {
wasm.main();
}
function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
wasm.__wbindgen_export_2(addHeapObject(e));
}
}
function isLikeNone(x) {
return x === undefined || x === null;
}
async function load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) {
if (module.headers.get('Content-Type') != 'application/wasm') {
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
} else {
throw e;
}
}
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else {
return instance;
}
}
}
function getImports() {
const imports = {};
imports.wbg = {};
imports.wbg.__wbg_alert_02b82f812a9453a9 = function(arg0, arg1) {
alert(getStringFromWasm0(arg0, arg1));
};
imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
const ret = getStringFromWasm0(arg0, arg1);
return addHeapObject(ret);
};
imports.wbg.__wbg_log_4b5638ad60bdc54a = function(arg0) {
console.log(getObject(arg0));
};
imports.wbg.__wbindgen_object_drop_ref = function(arg0) {
takeObject(arg0);
};
imports.wbg.__wbg_self_6d479506f72c6a71 = function() { return handleError(function () {
const ret = self.self;
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_window_f2557cc78490aceb = function() { return handleError(function () {
const ret = window.window;
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_globalThis_7f206bda628d5286 = function() { return handleError(function () {
const ret = globalThis.globalThis;
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_global_ba75c50d1cf384f4 = function() { return handleError(function () {
const ret = global.global;
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbindgen_is_undefined = function(arg0) {
const ret = getObject(arg0) === undefined;
return ret;
};
imports.wbg.__wbg_newnoargs_b5b063fc6c2f0376 = function(arg0, arg1) {
const ret = new Function(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
imports.wbg.__wbg_call_97ae9d8645dc388b = function() { return handleError(function (arg0, arg1) {
const ret = getObject(arg0).call(getObject(arg1));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
const ret = getObject(arg0);
return addHeapObject(ret);
};
imports.wbg.__wbg_instanceof_Window_acc97ff9f5d2c7b4 = function(arg0) {
let result;
try {
result = getObject(arg0) instanceof Window;
} catch {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_document_3ead31dbcad65886 = function(arg0) {
const ret = getObject(arg0).document;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_body_3cb4b4042b9a632b = function(arg0) {
const ret = getObject(arg0).body;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_createElement_976dbb84fe1661b5 = function() { return handleError(function (arg0, arg1, arg2) {
const ret = getObject(arg0).createElement(getStringFromWasm0(arg1, arg2));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_setinnerHTML_32081d8a164e6dc4 = function(arg0, arg1, arg2) {
getObject(arg0).innerHTML = getStringFromWasm0(arg1, arg2);
};
imports.wbg.__wbg_appendChild_e513ef0e5098dfdd = function() { return handleError(function (arg0, arg1) {
const ret = getObject(arg0).appendChild(getObject(arg1));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
imports.wbg.__wbindgen_rethrow = function(arg0) {
throw takeObject(arg0);
};
return imports;
}
function initMemory(imports, maybe_memory) {
}
function finalizeInit(instance, module) {
wasm = instance.exports;
init.__wbindgen_wasm_module = module;
cachedUint8Memory0 = new Uint8Array();
wasm.__wbindgen_start();
return wasm;
}
function initSync(module) {
const imports = getImports();
initMemory(imports);
if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module);
}
const instance = new WebAssembly.Instance(module, imports);
return finalizeInit(instance, module);
}
async function init(input) {
if (typeof input === 'undefined') {
input = new URL('frontend_bg.wasm', import.meta.url);
}
const imports = getImports();
if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {
input = fetch(input);
}
initMemory(imports);
const { instance, module } = await load(await input, imports);
return finalizeInit(instance, module);
}
export { initSync }
export default init;

View file

@ -32,6 +32,15 @@ body {
background-color: $background; background-color: $background;
margin: 0px; margin: 0px;
.recipe-item {
padding: 4px;
}
.recipe-item-current {
padding: 3px;
border: 1px solid white;
}
/* /*
.header-container { .header-container {

View file

@ -8,6 +8,14 @@
</head> </head>
<body> <body>
<script type="module">
import init from '/static/frontend.js';
async function run() {
await init();
}
run();
</script>
{% block body_container %}{% endblock %} {% block body_container %}{% endblock %}
<div class="footer-container">gburri - 2022</div> <div class="footer-container">gburri - 2022</div>
</body> </body>

View file

@ -2,13 +2,17 @@
{% block body_container %} {% block body_container %}
<div class="header-container"> <div class="header-container">
<h1><a href="/">~~ Recettes de cuisine ~~</a></h1> <a class="title" href="/">~~ Recettes de cuisine ~~</a>
<span class="create-recipe">Create a new recipe</span>
{% match user %} {% match user %}
{% when Some with (user) %} {% when Some with (user) %}
<div>{{ user.email }} / <a href="/signout" />Sign out</a></div> <span>{{ user.email }} / <a href="/signout" />Sign out</a></span>
{% when None %} {% when None %}
<div><a href="/signin" >Sign in</a> / <a href="/signup">Sign up</a></div> <span><a href="/signin" >Sign in</a> / <a href="/signup">Sign up</a></span>
{% endmatch %} {% endmatch %}
</div> </div>
<div class="main-container"> <div class="main-container">
{% block main_container %}{% endblock %} {% block main_container %}{% endblock %}

View file

@ -1,22 +1,25 @@
{% extends "base_with_header.html" %} {% extends "base_with_header.html" %}
{% macro recipe_item(id, title, class) %}
<a href="/recipe/view/{{ id }}" class="{{ class }}">{{ title }}</a>
{% endmacro %}
{% block main_container %} {% block main_container %}
<div class="list"> <div class="list">
<ul> <ul>
{% for (id, title) in recipes %} {% for (id, title) in recipes %}
<li> <li>
{% let item_html = "<a href=\"/recipe/view/{}\">{}</a>"|format(id, title) %}
{% match current_recipe_id %} {% match current_recipe_id %}
{# Don't know how to avoid repetition: comparing (using '==' or .eq()) current_recipe_id.unwrap() and id doesn't work. Guards for match don't exist. {# Don't know how to avoid repetition: comparing (using '==' or .eq()) current_recipe_id.unwrap() and id doesn't work. Guards for match don't exist.
See: https://github.com/djc/askama/issues/752 #} See: https://github.com/djc/askama/issues/752 #}
{% when Some (current_id) %} {% when Some (current_id) %}
{% if current_id == id %} {% if current_id == id %}
[{{ item_html|escape("none") }}] {% call recipe_item(id, title, "recipe-item-current") %}
{% else %} {% else %}
{{ item_html|escape("none") }} {% call recipe_item(id, title, "recipe-item") %}
{% endif %} {% endif %}
{% when None %} {% when None %}
{{ item_html|escape("none") }} {% call recipe_item(id, title, "recipe-item") %}
{% endmatch %} {% endmatch %}
</li> </li>
{% endfor %} {% endfor %}

39
frontend/Cargo.toml Normal file
View file

@ -0,0 +1,39 @@
[package]
name = "frontend"
version = "0.1.0"
authors = ["Greg Burri <greg.burri@gmail.com>"]
edition = "2021"
[lib]
crate-type = ["cdylib"]
[features]
default = ["console_error_panic_hook"]
[dependencies]
common = {path = "../common"}
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ['console', 'Document', 'Element', 'HtmlElement', 'Node', 'Window'] }
# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1", optional = true }
# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size
# compared to the default allocator's ~10K. It is slower than the default
# allocator, however.
wee_alloc = { version = "0.4", optional = true }
# [dev-dependencies]
# wasm-bindgen-test = "0.3"
[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"
lto = true
[package.metadata.wasm-pack.profile.release]
wasm-opt = false

3
frontend/deploy.nu Normal file
View file

@ -0,0 +1,3 @@
wasm-pack build --target web
cp pkg/frontend.js ../backend/static
cp pkg/frontend_bg.wasm ../backend/static

8
frontend/index.js Normal file
View file

@ -0,0 +1,8 @@
// Note that a dynamic `import` statement here is required due to
// webpack/webpack#6615, but in theory `import { greet } from './pkg';`
// will work here one day as well!
const rust = import('./pkg');
rust
.then(m => m.greet('Paul!'))
.catch(console.error);

14
frontend/package.json Normal file
View file

@ -0,0 +1,14 @@
{
"scripts": {
"build": "webpack",
"serve": "webpack serve"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "1.5.0",
"html-webpack-plugin": "^5.3.2",
"text-encoding": "^0.7.0",
"webpack": "^5.75.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^3.11.2"
}
}

35
frontend/src/lib.rs Normal file
View file

@ -0,0 +1,35 @@
mod utils;
use wasm_bindgen::prelude::*;
use web_sys::console;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
extern {
fn alert(s: &str);
}
#[wasm_bindgen]
pub fn greet(name: &str) {
alert(&format!("Hello, {}!", name));
console::log_1(&"Hello bg".into());
}
#[wasm_bindgen(start)]
pub fn main() -> Result<(), JsValue> {
let window = web_sys::window().expect("no global `window` exists");
let document = window.document().expect("should have a document on window");
let body = document.body().expect("document should have a body");
let val = document.create_element("p")?;
val.set_inner_html("Hello from Rust!");
body.append_child(&val)?;
Ok(())
}

10
frontend/src/utils.rs Normal file
View file

@ -0,0 +1,10 @@
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}

1
frontend/start.nu Normal file
View file

@ -0,0 +1 @@
npm run serve

13
frontend/tests/web.rs Normal file
View file

@ -0,0 +1,13 @@
//! Test suite for the Web and headless browsers.
#![cfg(target_arch = "wasm32")]
extern crate wasm_bindgen_test;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn pass() {
assert_eq!(1 + 1, 2);
}

View file

@ -0,0 +1,28 @@
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
},
plugins: [
new HtmlWebpackPlugin(),
new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, ".")
}),
// Have this example work in Edge which doesn't ship `TextEncoder` or
// `TextDecoder` at this time.
new webpack.ProvidePlugin({
TextDecoder: ['text-encoding', 'TextDecoder'],
TextEncoder: ['text-encoding', 'TextEncoder']
})
],
mode: 'development',
experiments: {
asyncWebAssembly: true
}
};