53 lines
1.3 KiB
Rust
Raw Normal View History

2019-08-14 13:31:26 +03:00
use fluence::sdk::*;
2019-08-14 22:15:38 +03:00
2019-08-14 23:22:15 +03:00
use log::info;
use api::Request;
use api::Response;
use crate::api::{AppResult, Post};
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-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-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-14 22:15:38 +03:00
model::add_post(msg, handle)?;
let count = model::get_posts_count()?;
2019-08-14 23:22:15 +03:00
Ok(Response::Post { count })
2019-08-14 13:31:26 +03:00
}
2019-08-14 23:22:15 +03:00
fn fetch_posts(_handle: Option<String>) -> AppResult<Response> {
2019-08-14 22:15:38 +03:00
// TODO: filter posts by handle
2019-08-14 23:22:15 +03:00
let posts_str = model::get_posts()?;
info!("posts_str {}", posts_str);
let posts: Vec<Post> = serde_json::from_str(posts_str.as_str())
.map_err(|e| err_msg(&format!("Can't parse posts {:?} to json: {}", posts_str, e)))?;
Ok(Response::Fetch { posts })
2019-08-14 22:15:38 +03:00
}