From 3826496a4029e92b6767c1fbb661229c3e3c8fa9 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sat, 11 Jan 2025 13:24:29 +0800 Subject: [PATCH 1/9] Add sqlite/wasm example --- Cargo.toml | 4 +- examples/sqlite/wasm/.gitignore | 1 + examples/sqlite/wasm/Cargo.toml | 16 +++ examples/sqlite/wasm/README.md | 18 +++ examples/sqlite/wasm/index.html | 70 ++++++++++ .../20170124012402_create_posts/down.sql | 1 + .../20170124012402_create_posts/up.sql | 6 + examples/sqlite/wasm/src/lib.rs | 129 ++++++++++++++++++ examples/sqlite/wasm/src/models.rs | 20 +++ examples/sqlite/wasm/src/schema.rs | 10 ++ 10 files changed, 274 insertions(+), 1 deletion(-) create mode 100644 examples/sqlite/wasm/.gitignore create mode 100644 examples/sqlite/wasm/Cargo.toml create mode 100644 examples/sqlite/wasm/README.md create mode 100644 examples/sqlite/wasm/index.html create mode 100644 examples/sqlite/wasm/migrations/20170124012402_create_posts/down.sql create mode 100644 examples/sqlite/wasm/migrations/20170124012402_create_posts/up.sql create mode 100644 examples/sqlite/wasm/src/lib.rs create mode 100644 examples/sqlite/wasm/src/models.rs create mode 100644 examples/sqlite/wasm/src/schema.rs diff --git a/Cargo.toml b/Cargo.toml index 986faaed41d4..c6d61c98c507 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,7 +30,9 @@ members = [ "examples/sqlite/getting_started_step_1", "examples/sqlite/getting_started_step_2", "examples/sqlite/getting_started_step_3", - "examples/sqlite/relations", "xtask", + "examples/sqlite/relations", + "examples/sqlite/wasm", + "xtask", ] [workspace.package] diff --git a/examples/sqlite/wasm/.gitignore b/examples/sqlite/wasm/.gitignore new file mode 100644 index 000000000000..5fff1d9c1889 --- /dev/null +++ b/examples/sqlite/wasm/.gitignore @@ -0,0 +1 @@ +pkg diff --git a/examples/sqlite/wasm/Cargo.toml b/examples/sqlite/wasm/Cargo.toml new file mode 100644 index 000000000000..f831dee22465 --- /dev/null +++ b/examples/sqlite/wasm/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "sqlite-wasm" +version = "0.1.0" +edition.workspace = true +publish = false + +[dependencies] +diesel = { path = "../../../diesel", features = ["sqlite", "returning_clauses_for_sqlite_3_35"] } +diesel_migrations = { path = "../../../diesel_migrations", features = ["sqlite"] } +serde = { version = "1.0.217", features = ["derive"] } +serde-wasm-bindgen = "0.6.5" +wasm-bindgen = "0.2.99" +wasm-bindgen-futures = "0.4.49" + +[lib] +crate-type = ["cdylib"] diff --git a/examples/sqlite/wasm/README.md b/examples/sqlite/wasm/README.md new file mode 100644 index 000000000000..65622f625e7a --- /dev/null +++ b/examples/sqlite/wasm/README.md @@ -0,0 +1,18 @@ +# `rs-diesel-sqlite-wasm` + +Diesel's `Getting Started` guide using SQLite instead of Postgresql + +## Usage + +``` +rustup target add wasm32-unknown-unknown +# Add wasm32-unknown-unknown toolchain + +cargo install wasm-pack + +wasm-pack build --web +# Build wasm + +python3 -m http.server 8000 +# Next, use it on the web page +``` diff --git a/examples/sqlite/wasm/index.html b/examples/sqlite/wasm/index.html new file mode 100644 index 000000000000..416fcc579f00 --- /dev/null +++ b/examples/sqlite/wasm/index.html @@ -0,0 +1,70 @@ + + + + + + sqlite-wasm example + + + + +

+ + + + +

+ + + +

+ + + +

+ + + +

+ + + + + \ No newline at end of file diff --git a/examples/sqlite/wasm/migrations/20170124012402_create_posts/down.sql b/examples/sqlite/wasm/migrations/20170124012402_create_posts/down.sql new file mode 100644 index 000000000000..c818e1985ba2 --- /dev/null +++ b/examples/sqlite/wasm/migrations/20170124012402_create_posts/down.sql @@ -0,0 +1 @@ +-- DROP TABLE posts diff --git a/examples/sqlite/wasm/migrations/20170124012402_create_posts/up.sql b/examples/sqlite/wasm/migrations/20170124012402_create_posts/up.sql new file mode 100644 index 000000000000..63953158929e --- /dev/null +++ b/examples/sqlite/wasm/migrations/20170124012402_create_posts/up.sql @@ -0,0 +1,6 @@ +CREATE TABLE posts ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + title VARCHAR NOT NULL, + body TEXT NOT NULL, + published BOOLEAN NOT NULL DEFAULT 0 +) diff --git a/examples/sqlite/wasm/src/lib.rs b/examples/sqlite/wasm/src/lib.rs new file mode 100644 index 000000000000..9fe51284a6a9 --- /dev/null +++ b/examples/sqlite/wasm/src/lib.rs @@ -0,0 +1,129 @@ +pub mod models; +pub mod schema; + +use std::sync::Once; + +use crate::models::{NewPost, Post}; +use diesel::prelude::*; +use diesel_migrations::EmbeddedMigrations; +use diesel_migrations::MigrationHarness; +use diesel_migrations::embed_migrations; +use wasm_bindgen::prelude::*; + +const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations"); + +#[wasm_bindgen] +extern "C" { + // Use `js_namespace` here to bind `console.log(..)` instead of just + // `log(..)` + #[wasm_bindgen(js_namespace = console)] + fn log(s: &str); +} + +// Next let's define a macro that's like `println!`, only it works for +// `console.log`. Note that `println!` doesn't actually work on the Wasm target +// because the standard library currently just eats all output. To get +// `println!`-like behavior in your app you'll likely want a macro like this. +macro_rules! console_log { + // Note that this is using the `log` function imported above during + // `bare_bones` + ($($t:tt)*) => (log(&format_args!($($t)*).to_string())) +} + +pub fn establish_connection() -> SqliteConnection { + static MIGRATION_ONCE: Once = Once::new(); + let mut conn = SqliteConnection::establish("post.db") + .unwrap_or_else(|_| panic!("Error connecting to post.db")); + MIGRATION_ONCE.call_once(|| { + conn.run_pending_migrations(MIGRATIONS).unwrap(); + }); + conn +} + +#[wasm_bindgen] +pub async fn init_sqlite() { + diesel::init_sqlite().await.unwrap(); +} + +#[wasm_bindgen] +pub fn create_post(title: &str, body: &str) -> JsValue { + use crate::schema::posts; + + let new_post = NewPost { title, body }; + + let post = diesel::insert_into(posts::table) + .values(&new_post) + .returning(Post::as_returning()) + .get_result(&mut establish_connection()) + .expect("Error saving new post"); + + serde_wasm_bindgen::to_value(&post).unwrap() +} + +#[wasm_bindgen] +pub fn delete_post(pattern: &str) { + let connection = &mut establish_connection(); + let num_deleted = diesel::delete( + schema::posts::dsl::posts.filter(schema::posts::title.like(pattern.to_string())), + ) + .execute(connection) + .expect("Error deleting posts"); + + console_log!("Deleted {num_deleted} posts"); +} + +#[wasm_bindgen] +pub fn get_post(post_id: i32) -> JsValue { + use schema::posts::dsl::posts; + + let connection = &mut establish_connection(); + + let post = posts + .find(post_id) + .select(Post::as_select()) + .first(connection) + .optional(); // This allows for returning an Option, otherwise it will throw an error + + match &post { + Ok(Some(post)) => console_log!("Post with id: {} has a title: {}", post.id, post.title), + Ok(None) => console_log!("Unable to find post {}", post_id), + Err(_) => console_log!("An error occurred while fetching post {}", post_id), + } + serde_wasm_bindgen::to_value(&post.ok().flatten()).unwrap() +} + +#[wasm_bindgen] +pub fn publish_post(id: i32) { + let connection = &mut establish_connection(); + + let post = diesel::update(schema::posts::dsl::posts.find(id)) + .set(schema::posts::dsl::published.eq(true)) + .returning(Post::as_returning()) + .get_result(connection) + .unwrap(); + + console_log!("Published post {}", post.title); +} + +#[wasm_bindgen] +pub fn show_posts() -> Vec { + let connection = &mut establish_connection(); + let results = schema::posts::dsl::posts + .filter(schema::posts::dsl::published.eq(true)) + .limit(5) + .select(Post::as_select()) + .load(connection) + .expect("Error loading posts"); + + console_log!("Displaying {} posts", results.len()); + for post in &results { + console_log!("{}", post.title); + console_log!("----------\n"); + console_log!("{}", post.body); + } + + results + .into_iter() + .map(|x| serde_wasm_bindgen::to_value(&x).unwrap()) + .collect() +} diff --git a/examples/sqlite/wasm/src/models.rs b/examples/sqlite/wasm/src/models.rs new file mode 100644 index 000000000000..5e0ea29c5aed --- /dev/null +++ b/examples/sqlite/wasm/src/models.rs @@ -0,0 +1,20 @@ +use super::schema::posts; +use diesel::prelude::*; +use serde::Serialize; + +#[derive(Queryable, Selectable, Serialize)] +#[diesel(table_name = posts)] +#[diesel(check_for_backend(diesel::sqlite::Sqlite))] +pub struct Post { + pub id: i32, + pub title: String, + pub body: String, + pub published: bool, +} + +#[derive(Insertable)] +#[diesel(table_name = posts)] +pub struct NewPost<'a> { + pub title: &'a str, + pub body: &'a str, +} diff --git a/examples/sqlite/wasm/src/schema.rs b/examples/sqlite/wasm/src/schema.rs new file mode 100644 index 000000000000..af8680bb82dc --- /dev/null +++ b/examples/sqlite/wasm/src/schema.rs @@ -0,0 +1,10 @@ +// @generated automatically by Diesel CLI. + +diesel::table! { + posts (id) { + id -> Integer, + title -> Text, + body -> Text, + published -> Bool, + } +} From 15a01b4f9410885281a82eb6cefb8e297f512ac5 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sun, 12 Jan 2025 00:11:40 +0800 Subject: [PATCH 2/9] Persistent storage example --- examples/sqlite/wasm/Cargo.toml | 2 +- examples/sqlite/wasm/README.md | 2 +- examples/sqlite/wasm/index.html | 64 +++++++++++++++++++++---------- examples/sqlite/wasm/src/lib.rs | 8 ++-- examples/sqlite/wasm/worker.js | 68 +++++++++++++++++++++++++++++++++ 5 files changed, 119 insertions(+), 25 deletions(-) create mode 100644 examples/sqlite/wasm/worker.js diff --git a/examples/sqlite/wasm/Cargo.toml b/examples/sqlite/wasm/Cargo.toml index f831dee22465..85f38b8e60b3 100644 --- a/examples/sqlite/wasm/Cargo.toml +++ b/examples/sqlite/wasm/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "sqlite-wasm" +name = "sqlite-wasm-example" version = "0.1.0" edition.workspace = true publish = false diff --git a/examples/sqlite/wasm/README.md b/examples/sqlite/wasm/README.md index 65622f625e7a..4464ad38eddb 100644 --- a/examples/sqlite/wasm/README.md +++ b/examples/sqlite/wasm/README.md @@ -1,4 +1,4 @@ -# `rs-diesel-sqlite-wasm` +# `rs-diesel-sqlite` Diesel's `Getting Started` guide using SQLite instead of Postgresql diff --git a/examples/sqlite/wasm/index.html b/examples/sqlite/wasm/index.html index 416fcc579f00..95ab90865984 100644 --- a/examples/sqlite/wasm/index.html +++ b/examples/sqlite/wasm/index.html @@ -3,7 +3,7 @@ - sqlite-wasm example + diesel sqlite-wasm example @@ -21,50 +21,74 @@ -

+

- + -

+

- \ No newline at end of file + diff --git a/examples/sqlite/wasm/src/lib.rs b/examples/sqlite/wasm/src/lib.rs index 9fe51284a6a9..031bf069d157 100644 --- a/examples/sqlite/wasm/src/lib.rs +++ b/examples/sqlite/wasm/src/lib.rs @@ -5,9 +5,9 @@ use std::sync::Once; use crate::models::{NewPost, Post}; use diesel::prelude::*; +use diesel_migrations::embed_migrations; use diesel_migrations::EmbeddedMigrations; use diesel_migrations::MigrationHarness; -use diesel_migrations::embed_migrations; use wasm_bindgen::prelude::*; const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations"); @@ -32,7 +32,7 @@ macro_rules! console_log { pub fn establish_connection() -> SqliteConnection { static MIGRATION_ONCE: Once = Once::new(); - let mut conn = SqliteConnection::establish("post.db") + let mut conn = SqliteConnection::establish("file:post.db?vfs=opfs-sahpool") .unwrap_or_else(|_| panic!("Error connecting to post.db")); MIGRATION_ONCE.call_once(|| { conn.run_pending_migrations(MIGRATIONS).unwrap(); @@ -40,9 +40,11 @@ pub fn establish_connection() -> SqliteConnection { conn } +#[cfg(all(target_family = "wasm", target_os = "unknown"))] #[wasm_bindgen] pub async fn init_sqlite() { - diesel::init_sqlite().await.unwrap(); + let sqlite = diesel::init_sqlite().await.unwrap(); + sqlite.install_opfs_sahpool(None).await.unwrap(); } #[wasm_bindgen] diff --git a/examples/sqlite/wasm/worker.js b/examples/sqlite/wasm/worker.js new file mode 100644 index 000000000000..5c2aa41a5fa6 --- /dev/null +++ b/examples/sqlite/wasm/worker.js @@ -0,0 +1,68 @@ +import init, { + init_sqlite, + create_post, + get_post, + delete_post, + publish_post, + show_posts +} from "./pkg/sqlite_wasm_example.js"; + +await init(); +await init_sqlite(); + +async function run_in_worker(event) { + const payload = event.data; + switch (payload.cmd) { + case 'show_posts': + var posts = show_posts(); + self.postMessage( + { + cmd: 'show_posts', + posts: posts + } + ); + break; + case 'create_post': + var post = create_post(payload.title, payload.body); + self.postMessage( + { + cmd: 'create_post', + post: post, + } + ); + break; + case 'get_post': + var post = get_post(payload.post_id); + self.postMessage( + { + cmd: 'get_post', + post: post, + } + ); + break; + case 'publish_post': + publish_post(payload.post_id); + self.postMessage( + { + cmd: 'publish_post', + } + ); + break; + case 'delete_post': + delete_post(payload.title); + self.postMessage( + { + cmd: 'delete_post', + } + ); + break; + default: + break; + }; +} + +self.onmessage = function (event) { + run_in_worker(event); +} + +self.postMessage("ready"); From 1bc65901b55570f0638227b2437da885e1f2f1d9 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sun, 19 Jan 2025 22:22:04 +0800 Subject: [PATCH 3/9] Add COEP and COOP headers to enable opfs vfs --- examples/sqlite/wasm/server.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 examples/sqlite/wasm/server.py diff --git a/examples/sqlite/wasm/server.py b/examples/sqlite/wasm/server.py new file mode 100644 index 000000000000..8886642ae302 --- /dev/null +++ b/examples/sqlite/wasm/server.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +from http.server import HTTPServer, SimpleHTTPRequestHandler, test +import sys + +class RequestHandler(SimpleHTTPRequestHandler): + def end_headers(self): + self.send_header('Cross-Origin-Opener-Policy', 'same-origin') + self.send_header('Cross-Origin-Embedder-Policy', 'require-corp') + SimpleHTTPRequestHandler.end_headers(self) + +if __name__ == '__main__': + test(RequestHandler, HTTPServer, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000) From 41ef342d2ff0bcfbd98e5bd084fd511388c694c8 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sun, 19 Jan 2025 22:24:43 +0800 Subject: [PATCH 4/9] Fix build command --- examples/sqlite/wasm/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/sqlite/wasm/README.md b/examples/sqlite/wasm/README.md index 4464ad38eddb..ec80a669fd05 100644 --- a/examples/sqlite/wasm/README.md +++ b/examples/sqlite/wasm/README.md @@ -10,7 +10,7 @@ rustup target add wasm32-unknown-unknown cargo install wasm-pack -wasm-pack build --web +wasm-pack build --target web # Build wasm python3 -m http.server 8000 From 97881795f97a900c337f27f23e14d4fe30684861 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sun, 19 Jan 2025 22:27:52 +0800 Subject: [PATCH 5/9] Drop posts in down migration --- .../sqlite/wasm/migrations/20170124012402_create_posts/down.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/sqlite/wasm/migrations/20170124012402_create_posts/down.sql b/examples/sqlite/wasm/migrations/20170124012402_create_posts/down.sql index c818e1985ba2..b1eab722bc18 100644 --- a/examples/sqlite/wasm/migrations/20170124012402_create_posts/down.sql +++ b/examples/sqlite/wasm/migrations/20170124012402_create_posts/down.sql @@ -1 +1 @@ --- DROP TABLE posts +DROP TABLE posts From 8f743001aa40bd5bae9d31d872c8fe69f50f6cdd Mon Sep 17 00:00:00 2001 From: Spxg Date: Sun, 19 Jan 2025 22:35:07 +0800 Subject: [PATCH 6/9] Make server.py executable --- examples/sqlite/wasm/server.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 examples/sqlite/wasm/server.py diff --git a/examples/sqlite/wasm/server.py b/examples/sqlite/wasm/server.py old mode 100644 new mode 100755 From d1a3763f3d69a6b2fd87bdcb5dfc76e1c12d3096 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sun, 19 Jan 2025 23:07:00 +0800 Subject: [PATCH 7/9] Support switching VFS --- examples/sqlite/wasm/index.html | 15 +++++++++++++++ examples/sqlite/wasm/src/lib.rs | 22 ++++++++++++++++++---- examples/sqlite/wasm/worker.js | 4 ++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/examples/sqlite/wasm/index.html b/examples/sqlite/wasm/index.html index 95ab90865984..a9ce90549262 100644 --- a/examples/sqlite/wasm/index.html +++ b/examples/sqlite/wasm/index.html @@ -7,6 +7,15 @@ + + + +

+

@@ -33,6 +42,11 @@ } async function run() { + document.getElementById('SwitchVFS').onclick = () => { + const id = parseInt(document.getElementById('vfs').value); + call({ cmd: "switch_vfs", id: id }) + }; + document.getElementById('ShowButton').onclick = () => { call({ cmd: "show_posts" }) }; @@ -58,6 +72,7 @@ call({ cmd: "delete_post", title: title }) }; } + const worker = new Worker('worker.js', { type: 'module' }); worker.addEventListener("message", function (event) { const payload = event.data; diff --git a/examples/sqlite/wasm/src/lib.rs b/examples/sqlite/wasm/src/lib.rs index 031bf069d157..65b9f63d4c85 100644 --- a/examples/sqlite/wasm/src/lib.rs +++ b/examples/sqlite/wasm/src/lib.rs @@ -1,6 +1,7 @@ pub mod models; pub mod schema; +use std::sync::Mutex; use std::sync::Once; use crate::models::{NewPost, Post}; @@ -30,11 +31,19 @@ macro_rules! console_log { ($($t:tt)*) => (log(&format_args!($($t)*).to_string())) } +static VFS: Mutex<(i32, Once)> = Mutex::new((0, Once::new())); + pub fn establish_connection() -> SqliteConnection { - static MIGRATION_ONCE: Once = Once::new(); - let mut conn = SqliteConnection::establish("file:post.db?vfs=opfs-sahpool") - .unwrap_or_else(|_| panic!("Error connecting to post.db")); - MIGRATION_ONCE.call_once(|| { + let (vfs, once) = &*VFS.lock().unwrap(); + let url = match vfs { + 0 => "post.db", + 1 => "file:post.db?vfs=opfs", + 2 => "file:post.db?vfs=opfs-sahpool", + _ => unreachable!(), + }; + let mut conn = + SqliteConnection::establish(url).unwrap_or_else(|_| panic!("Error connecting to post.db")); + once.call_once(|| { conn.run_pending_migrations(MIGRATIONS).unwrap(); }); conn @@ -47,6 +56,11 @@ pub async fn init_sqlite() { sqlite.install_opfs_sahpool(None).await.unwrap(); } +#[wasm_bindgen] +pub fn switch_vfs(id: i32) { + *VFS.lock().unwrap() = (id, Once::new()); +} + #[wasm_bindgen] pub fn create_post(title: &str, body: &str) -> JsValue { use crate::schema::posts; diff --git a/examples/sqlite/wasm/worker.js b/examples/sqlite/wasm/worker.js index 5c2aa41a5fa6..d1ed02e90632 100644 --- a/examples/sqlite/wasm/worker.js +++ b/examples/sqlite/wasm/worker.js @@ -1,5 +1,6 @@ import init, { init_sqlite, + switch_vfs, create_post, get_post, delete_post, @@ -13,6 +14,9 @@ await init_sqlite(); async function run_in_worker(event) { const payload = event.data; switch (payload.cmd) { + case 'switch_vfs': + switch_vfs(payload.id); + break; case 'show_posts': var posts = show_posts(); self.postMessage( From 9231453b7e909a29780571f96ab55d9fcc006da5 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sun, 19 Jan 2025 23:10:25 +0800 Subject: [PATCH 8/9] Update wasm example readme --- examples/sqlite/wasm/README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/examples/sqlite/wasm/README.md b/examples/sqlite/wasm/README.md index ec80a669fd05..0855a5792459 100644 --- a/examples/sqlite/wasm/README.md +++ b/examples/sqlite/wasm/README.md @@ -4,15 +4,20 @@ Diesel's `Getting Started` guide using SQLite instead of Postgresql ## Usage +Compile wasm and start the web server: + ``` rustup target add wasm32-unknown-unknown # Add wasm32-unknown-unknown toolchain cargo install wasm-pack +# Install the wasm-pack toolchain wasm-pack build --target web # Build wasm -python3 -m http.server 8000 -# Next, use it on the web page +python3 server.py +# Start server ``` + +Next, try it on the web page: [on the web page](http://localhost:8000) From 1793051c01cfdab0799bcafc60a457d7c1dbc783 Mon Sep 17 00:00:00 2001 From: Spxg Date: Tue, 21 Jan 2025 01:03:13 +0800 Subject: [PATCH 9/9] Update onmessage event --- examples/sqlite/wasm/index.html | 57 ++++++++++++++++----------------- 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/examples/sqlite/wasm/index.html b/examples/sqlite/wasm/index.html index a9ce90549262..e2b761a550b6 100644 --- a/examples/sqlite/wasm/index.html +++ b/examples/sqlite/wasm/index.html @@ -74,35 +74,34 @@ } const worker = new Worker('worker.js', { type: 'module' }); - worker.addEventListener("message", function (event) { - const payload = event.data; - switch (payload.cmd) { - case 'ready': - run(); - break; - case 'show_posts': - var posts = payload.posts; - document.getElementById('show_result').innerText = JSON.stringify(posts); - break; - case 'create_post': - var post = payload.post; - document.getElementById('create_result').innerText = JSON.stringify(post); - break; - case 'get_post': - var post = payload.post; - document.getElementById('get_result').innerText = JSON.stringify(post); - break; - case 'publish_post': - document.getElementById('publish_result').innerText = 'Publish done.'; - break; - case 'delete_post': - document.getElementById('delete_result').innerText = 'Delete done.'; - break; - default: - break; - }; - }); - run(); + worker.onmessage = function (event) { + run(); + worker.onmessage = function (event) { + const payload = event.data; + switch (payload.cmd) { + case 'show_posts': + var posts = payload.posts; + document.getElementById('show_result').innerText = JSON.stringify(posts); + break; + case 'create_post': + var post = payload.post; + document.getElementById('create_result').innerText = JSON.stringify(post); + break; + case 'get_post': + var post = payload.post; + document.getElementById('get_result').innerText = JSON.stringify(post); + break; + case 'publish_post': + document.getElementById('publish_result').innerText = 'Publish done.'; + break; + case 'delete_post': + document.getElementById('delete_result').innerText = 'Delete done.'; + break; + default: + break; + }; + } + }