63 lines
1.6 KiB
Rust
Raw Normal View History

2019-08-14 13:31:26 +03:00
use fluence::sdk::*;
2019-08-15 00:05:00 +03:00
use serde_json::value::RawValue;
2019-08-14 23:22:15 +03:00
use api::Request;
use api::Response;
2019-08-15 00:05:00 +03:00
use crate::api::AppResult;
2019-08-14 23:22:15 +03:00
use crate::errors::err_msg;
2019-08-14 22:15:38 +03:00
pub mod api;
pub mod database;
pub mod errors;
pub mod ffi;
pub mod model;
2019-08-14 13:31:26 +03:00
fn init() {
logger::WasmLogger::init_with_level(log::Level::Info).unwrap();
2019-08-14 22:15:38 +03:00
model::create_scheme().unwrap();
2019-08-14 13:31:26 +03:00
}
#[invocation_handler(init_fn = init)]
2019-08-14 20:19:39 +03:00
fn run(arg: String) -> String {
2019-08-15 15:02:52 +03:00
// Parse and handle JSON request
2019-08-14 22:15:38 +03:00
let result = api::parse(arg).and_then(|request| match request {
Request::Post { msg, handle } => add_post(msg, handle),
Request::Fetch { handle } => fetch_posts(handle),
});
2019-08-14 14:02:22 +03:00
2019-08-14 22:15:38 +03:00
let result = match result {
Ok(good) => good,
2019-08-14 23:22:15 +03:00
Err(error) => Response::Error {
error: error.to_string(),
},
2019-08-14 22:15:38 +03:00
};
2019-08-14 13:31:26 +03:00
2019-08-15 15:02:52 +03:00
// Serialize response to JSON
2019-08-14 23:22:15 +03:00
api::serialize(&result)
2019-08-14 22:15:38 +03:00
}
2019-08-14 13:31:26 +03:00
2019-08-14 23:22:15 +03:00
fn add_post(msg: String, handle: String) -> AppResult<Response> {
2019-08-15 15:02:52 +03:00
// Store post
2019-08-14 22:15:38 +03:00
model::add_post(msg, handle)?;
2019-08-15 15:02:52 +03:00
// Get total number of posts
2019-08-14 22:15:38 +03:00
let count = model::get_posts_count()?;
2019-08-15 15:02:52 +03:00
2019-08-14 23:22:15 +03:00
Ok(Response::Post { count })
2019-08-14 13:31:26 +03:00
}
2019-08-15 13:00:52 +03:00
fn fetch_posts(handle: Option<String>) -> AppResult<Response> {
let posts_str = match handle {
2019-08-15 15:02:52 +03:00
// Get all posts if no filter handle was passed
2019-08-15 13:00:52 +03:00
None => model::get_all_posts()?,
2019-08-15 15:02:52 +03:00
// Or get only posts from specified author
Some(h) => model::get_posts_by_handle(h)?,
2019-08-15 13:00:52 +03:00
};
2019-08-15 15:02:52 +03:00
// Some Rust-specific detail to play nice with serialization, doesn't matter
2019-08-15 00:05:00 +03:00
let raw = RawValue::from_string(posts_str)
.map_err(|e| err_msg(&format!("Can't create RawValue: {}", e)))?;
2019-08-15 13:00:52 +03:00
2019-08-15 00:05:00 +03:00
Ok(Response::Fetch { posts: raw })
2019-08-14 22:15:38 +03:00
}