-
Notifications
You must be signed in to change notification settings - Fork 16
/
lib.rs
69 lines (55 loc) · 1.6 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use include_dir::{include_dir, Dir};
use serde::{Deserialize, Serialize};
use surrealdb::{engine::any::connect, sql::Thing};
use surrealdb_migrations::MigrationRunner;
use utils::set_panic_hook;
use wasm_bindgen::prelude::*;
mod utils;
// 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 "C" {}
#[wasm_bindgen]
pub async fn setup() {
set_panic_hook();
const DB_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/db");
let db = connect("indxdb://HelloDb")
.await
.expect("Failed to connect to database");
db.use_ns("test")
.use_db("test")
.await
.expect("Failed to use namespace");
MigrationRunner::new(&db)
.load_files(&DB_DIR)
.up()
.await
.expect("Failed to apply migrations");
}
#[wasm_bindgen]
pub async fn get_blog_posts() -> js_sys::Array {
set_panic_hook();
let db = connect("indxdb://HelloDb")
.await
.expect("Failed to connect to database");
db.use_ns("test")
.use_db("test")
.await
.expect("Failed to use namespace");
let posts: Vec<BlogPost> = db.select("post").await.expect("Failed to get blog posts");
posts
.into_iter()
.map(|post| serde_wasm_bindgen::to_value(&post).unwrap())
.collect::<js_sys::Array>()
}
#[wasm_bindgen]
#[derive(Debug, Serialize, Deserialize)]
struct BlogPost {
id: Thing,
title: String,
content: String,
status: String,
}