Add frontend tests and other stuff
This commit is contained in:
parent
d28e765e39
commit
642dd8a80c
26 changed files with 730 additions and 85 deletions
|
|
@ -1,7 +1,7 @@
|
|||
INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])
|
||||
VALUES (
|
||||
1,
|
||||
'paul@test.org',
|
||||
'paul@atreides.com',
|
||||
'paul',
|
||||
'$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',
|
||||
0,
|
||||
|
|
|
|||
|
|
@ -42,10 +42,21 @@ CREATE TABLE [Recipe] (
|
|||
[estimate_time] INTEGER,
|
||||
[description] TEXT,
|
||||
[servings] INTEGER DEFAULT 4,
|
||||
[is_published] INTEGER NOT NULL DEFAULT FALSE,
|
||||
|
||||
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] (
|
||||
[id] INTEGER PRIMARY KEY,
|
||||
|
||||
|
|
|
|||
|
|
@ -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>;
|
||||
|
||||
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();
|
||||
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();
|
||||
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();
|
||||
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();
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
@ -60,7 +60,7 @@ pub enum SignUpResult {
|
|||
pub enum ValidationResult {
|
||||
UnknownUser,
|
||||
ValidationExpired,
|
||||
Ok(String, i32), // Returns token and user id.
|
||||
Ok(String, i64), // Returns token and user id.
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -68,18 +68,17 @@ pub enum SignInResult {
|
|||
UserNotFound,
|
||||
WrongPassword,
|
||||
AccountNotValidated,
|
||||
Ok(String, i32), // Returns token and user id.
|
||||
Ok(String, i64), // Returns token and user id.
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AuthenticationResult {
|
||||
NotValidToken,
|
||||
Ok(i32), // Returns user id.
|
||||
Ok(i64), // Returns user id.
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Connection {
|
||||
//con: rusqlite::Connection
|
||||
pool: Pool<SqliteConnectionManager>
|
||||
}
|
||||
|
||||
|
|
@ -106,13 +105,13 @@ impl Connection {
|
|||
fn create_connection(manager: SqliteConnectionManager) -> Result<Connection> {
|
||||
let pool = r2d2::Pool::new(manager).unwrap();
|
||||
let connection = Connection { pool };
|
||||
connection.create_or_update()?;
|
||||
connection.create_or_update_db()?;
|
||||
Ok(connection)
|
||||
}
|
||||
|
||||
/// Called after the connection has been established for creating or updating 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.
|
||||
let mut con = self.pool.get()?;
|
||||
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 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| {
|
||||
Ok((row.get("id")?, row.get("title")?))
|
||||
})?.collect();
|
||||
|
|
@ -198,7 +197,7 @@ impl Connection {
|
|||
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()?;
|
||||
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")?))
|
||||
|
|
@ -216,7 +215,7 @@ impl Connection {
|
|||
}).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()?;
|
||||
con.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id], |r| {
|
||||
Ok(User {
|
||||
|
|
@ -234,7 +233,7 @@ impl Connection {
|
|||
let tx = con.transaction()?;
|
||||
let token =
|
||||
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()? {
|
||||
Some((id, validation_token)) => {
|
||||
if validation_token.is_none() {
|
||||
|
|
@ -261,7 +260,7 @@ impl Connection {
|
|||
let tx = con.transaction()?;
|
||||
let user_id =
|
||||
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()? {
|
||||
Some((id, creation_datetime)) => {
|
||||
if Utc::now() - creation_datetime > validation_time {
|
||||
|
|
@ -283,7 +282,7 @@ impl Connection {
|
|||
let mut con = self.pool.get()?;
|
||||
let tx = con.transaction()?;
|
||||
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()? {
|
||||
Some((id, stored_password, validation_token)) => {
|
||||
if validation_token.is_some() {
|
||||
|
|
@ -306,7 +305,7 @@ impl Connection {
|
|||
let mut con = self.pool.get()?;
|
||||
let tx = con.transaction()?;
|
||||
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()? {
|
||||
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])?;
|
||||
|
|
@ -322,7 +321,7 @@ impl Connection {
|
|||
let mut con = self.pool.get()?;
|
||||
let tx = con.transaction()?;
|
||||
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()? {
|
||||
Some(login_id) => {
|
||||
tx.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params![login_id])?;
|
||||
|
|
@ -333,6 +332,33 @@ impl Connection {
|
|||
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.
|
||||
pub fn execute_file<P: AsRef<Path> + fmt::Display>(&self, file: P) -> Result<()> {
|
||||
let con = self.pool.get()?;
|
||||
|
|
@ -348,7 +374,7 @@ impl Connection {
|
|||
}
|
||||
|
||||
// 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();
|
||||
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)
|
||||
|
|
@ -369,6 +395,7 @@ fn generate_token() -> String {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rusqlite::{Error, ErrorCode, ffi, types::Value};
|
||||
|
||||
#[test]
|
||||
fn sign_up() -> Result<()> {
|
||||
|
|
@ -603,4 +630,37 @@ mod tests {
|
|||
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
pub struct Recipe {
|
||||
pub id: i32,
|
||||
pub id: i64,
|
||||
pub title: String,
|
||||
pub description: Option<String>,
|
||||
pub estimate_time: Option<i32>, // [min].
|
||||
|
|
@ -10,7 +10,7 @@ pub struct 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 {
|
||||
id,
|
||||
title,
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ use crate::user::User;
|
|||
use crate::model;
|
||||
use crate::data::{db, asynchronous};
|
||||
|
||||
mod api;
|
||||
|
||||
///// UTILS /////
|
||||
|
||||
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")]
|
||||
struct HomeTemplate {
|
||||
user: Option<User>,
|
||||
recipes: Vec<(i32, String)>,
|
||||
current_recipe_id: Option<i32>,
|
||||
recipes: Vec<(i64, String)>,
|
||||
current_recipe_id: Option<i64>,
|
||||
}
|
||||
|
||||
#[get("/")]
|
||||
|
|
@ -137,13 +139,13 @@ pub async fn home_page(req: HttpRequest, connection: web::Data<db::Connection>)
|
|||
#[template(path = "view_recipe.html")]
|
||||
struct ViewRecipeTemplate {
|
||||
user: Option<User>,
|
||||
recipes: Vec<(i32, String)>,
|
||||
current_recipe_id: Option<i32>,
|
||||
recipes: Vec<(i64, String)>,
|
||||
current_recipe_id: Option<i64>,
|
||||
current_recipe: model::Recipe,
|
||||
}
|
||||
|
||||
#[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 user = get_current_user(&req, connection.clone()).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)) => {
|
||||
let url = {
|
||||
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();
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
27
backend/src/services/api.rs
Normal file
27
backend/src/services/api.rs
Normal 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
294
backend/static/frontend.js
Normal 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;
|
||||
|
|
@ -32,6 +32,15 @@ body {
|
|||
background-color: $background;
|
||||
margin: 0px;
|
||||
|
||||
.recipe-item {
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.recipe-item-current {
|
||||
padding: 3px;
|
||||
border: 1px solid white;
|
||||
}
|
||||
|
||||
/*
|
||||
.header-container {
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,14 @@
|
|||
</head>
|
||||
|
||||
<body>
|
||||
<script type="module">
|
||||
import init from '/static/frontend.js';
|
||||
async function run() {
|
||||
await init();
|
||||
}
|
||||
run();
|
||||
</script>
|
||||
|
||||
{% block body_container %}{% endblock %}
|
||||
<div class="footer-container">gburri - 2022</div>
|
||||
</body>
|
||||
|
|
|
|||
|
|
@ -2,13 +2,17 @@
|
|||
|
||||
{% block body_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 %}
|
||||
{% 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 %}
|
||||
<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 %}
|
||||
|
||||
</div>
|
||||
<div class="main-container">
|
||||
{% block main_container %}{% endblock %}
|
||||
|
|
|
|||
|
|
@ -1,22 +1,25 @@
|
|||
{% extends "base_with_header.html" %}
|
||||
|
||||
{% macro recipe_item(id, title, class) %}
|
||||
<a href="/recipe/view/{{ id }}" class="{{ class }}">{{ title }}</a>
|
||||
{% endmacro %}
|
||||
|
||||
{% block main_container %}
|
||||
<div class="list">
|
||||
<ul>
|
||||
{% for (id, title) in recipes %}
|
||||
<li>
|
||||
{% let item_html = "<a href=\"/recipe/view/{}\">{}</a>"|format(id, title) %}
|
||||
{% 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.
|
||||
See: https://github.com/djc/askama/issues/752 #}
|
||||
{% when Some (current_id) %}
|
||||
{% if current_id == id %}
|
||||
[{{ item_html|escape("none") }}]
|
||||
{% call recipe_item(id, title, "recipe-item-current") %}
|
||||
{% else %}
|
||||
{{ item_html|escape("none") }}
|
||||
{% call recipe_item(id, title, "recipe-item") %}
|
||||
{% endif %}
|
||||
{% when None %}
|
||||
{{ item_html|escape("none") }}
|
||||
{% call recipe_item(id, title, "recipe-item") %}
|
||||
{% endmatch %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue