61 lines
1.6 KiB
Rust
Raw Normal View History

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