rust-workshop => backend-rust

This commit is contained in:
folex
2019-08-16 16:49:07 +03:00
parent b85eea0963
commit 92af937fc7
31 changed files with 30 additions and 324 deletions

View File

@ -0,0 +1,30 @@
use crate::errors::{err_msg, Error};
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
pub type AppResult<T> = ::std::result::Result<T, Box<Error>>;
#[derive(Deserialize)]
#[serde(tag = "action")]
pub enum Request {
Post { message: String, username: String },
Fetch { username: Option<String> },
}
#[derive(Serialize, Debug)]
#[serde(untagged)]
pub enum Response {
Post { count: i32 },
Fetch { posts: Box<RawValue> },
Error { error: String },
}
pub fn parse(s: String) -> AppResult<Request> {
serde_json::from_str(s.as_str())
.map_err(|e| err_msg(&format!("unable to parse json request from {}: {}", s, e)))
}
pub fn serialize(response: &Response) -> String {
serde_json::to_string(response)
.unwrap_or(format!("Unable to serialize response {:?}", response))
}

View File

@ -0,0 +1,16 @@
use std::fmt;
#[derive(Debug)]
pub struct Error(String);
impl std::error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
pub fn err_msg(s: &str) -> Box<Error> {
Error(s.to_string()).into()
}

View File

@ -0,0 +1,60 @@
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 {
// Parse and username JSON request
let result = api::parse(arg).and_then(|request| match request {
Request::Post { message, username } => add_post(message, username),
Request::Fetch { username } => fetch_posts(username),
});
let result = match result {
Ok(good) => good,
Err(error) => Response::Error {
error: error.to_string(),
},
};
// Serialize response to JSON
api::serialize(&result)
}
fn add_post(msg: String, username: String) -> AppResult<Response> {
// Store post
model::add_post(msg, username)?;
// Get total number of posts
let count = model::get_posts_count()?;
Ok(Response::Post { count })
}
fn fetch_posts(username: Option<String>) -> AppResult<Response> {
let posts_str = match username {
// Get all posts if no filter username was passed
None => model::get_all_posts()?,
// Or get only posts from specified author
Some(h) => model::get_posts_by_username(h)?,
};
// 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 })
}

View File

@ -0,0 +1,25 @@
use crate::api::AppResult;
use log;
pub fn create_scheme() -> AppResult<()> {
Ok(log::info!("creating scheme"))
}
pub fn add_post(msg: String, username: String) -> AppResult<()> {
Ok(log::info!("add post {} {}", msg, username))
}
pub fn get_all_posts() -> AppResult<String> {
log::info!("get all posts");
Ok("[]".to_string())
}
pub fn get_posts_by_username(username: String) -> AppResult<String> {
log::info!("get all posts by username {}", username);
Ok("[]".to_string())
}
pub fn get_posts_count() -> AppResult<i32> {
log::info!("get posts count");
Ok(0)
}