#service #microservices #rest #sync #run-time #non-full #ras

ras_service

Simple library for build (non-full) REST microservice

1 unstable release

0.2.0 Mar 26, 2022
0.1.1 Mar 20, 2022
0.1.0 Mar 18, 2022

#123 in #microservices


Used in ras_auth

MIT license

21KB
505 lines

ras-service

Simple library for build (non-full) REST microservice

crates.io: https://crates.io/crates/ras_service docs.rs: https://docs.rs/ras_service/0.2.0/ras_service


lib.rs:

Simple library for build (non-full) REST microservice

Is used async tokio runtime.

To build runtime use method "get_runtime".

To create executor use method "new", borrowing runtime and service.

To add functions use functions "add_get_functions" and "add_post_functions".

Function name is last word in url.

Signature functions:

fn(Handle, Arc, Option<&str>) -> RasResult

Must return RasResult::Sync for sync call, and RasResult::Async for async call.

Sync contains HttpStatus and answer data. Async contains JoinHandle, wich will be awaited.

Examples

use ras_service::*;

// Your Service (used for contains resources, as discriptos or data)
// Must be Sync + Send
struct Service {
	some_data: String,
}

//Build your constructor here
impl Service {
	async fn new() -> Service {
		Service {
			some_data: "resource".to_string(),
		}
	}
}

//Sync get function
fn some_test_get(
	runtime: Handle,
	self_service: Arc<Service>,
	params: Option<&str>)
-> RasResult {
	let result = if let Some(param_str) = params {
		format!(
			"Your params: {:#?}",
   			ras_service::ras_helper::parse_get_params(param_str)
		)
	} else {
		"Empty params".to_string()
	};
	RasResult::Sync(
		HttpStatus::OK,
		Some(result)
	)
}

//Async post funtion
fn some_test_post(
	runtime: Handle,
	self_service: Arc<Service>,
	query: Option<&str>)
-> RasResult {
	let query: HashMap<String, Option<String>> = 
		if let Some(query_str) = query {
			match serde_json::from_str(query_str) {
				Ok(query) => query,
				Err(err) => {
					eprintln!("Error! Bad json format: {:?}", err);
					return RasResult::Sync(HttpStatus::BadRequest, None);
				}
			}
		} else {
			return RasResult::Sync(HttpStatus::BadRequest, None);
		};
	let service = self_service.clone();
	RasResult::Async(runtime.spawn(async move {
		let result = format!("You data: {:?}; Resource: {:?}", query, service.some_data);
		(HttpStatus::OK, Some(result))
	}))
}

fn main() {
	let runtime = RasServiceBuilder::<Service>::get_runtime(4);
	let service = runtime.block_on(async {Service::new().await});
	RasServiceBuilder::new(runtime, service)
		.set_socket_url("127.0.0.1:7878")
		.add_get_function("some_test".to_string(), some_test_get)
		.add_post_function("some_test".to_string(), some_test_post)
		//.run();
		;
     	assert_eq!(1, 1);
}

Dependencies

~8–20MB
~303K SLoC