Skip to content
Snippets Groups Projects
Commit f74d8421 authored by Michael Hauspie's avatar Michael Hauspie
Browse files

Refactor by moving operations to own module

parent ccda501f
No related branches found
No related tags found
No related merge requests found
use rocket::{get, launch, post, routes, serde::json::Json};
use serde::{Deserialize, Serialize};
const INDEX_TEXT: &str = r#"\
Cette application permet d'executer des calculs simple.
......@@ -30,16 +29,8 @@ Pour envoyer une requête avec curl:
curl -X POST http://monurl -H 'Content-Type: application/json' -d '{"Plus", [3, 4]}'
"#;
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
enum Operation {
Plus(i32,i32),
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
struct OperationResult {
operation: String,
resultat: i32,
}
mod operations;
use operations::{Operation, OperationResult};
#[get("/")]
fn index() -> &'static str {
......@@ -48,12 +39,7 @@ fn index() -> &'static str {
#[post("/", data = "<operation>")]
fn do_calc(operation: Json<Operation>) -> Json<OperationResult> {
match operation.into_inner() {
Operation::Plus(op1, op2) => OperationResult {
operation: format!("{op1} + {op2}"),
resultat: op1 + op2,
}.into()
}
OperationResult::from(operation.into_inner()).into()
}
#[get("/test")]
......@@ -91,10 +77,7 @@ mod tests {
let response = req.dispatch();
assert_eq!(response.status(), Status::Ok);
let expected = OperationResult {
operation: "3 + 8".into(),
resultat: 11,
};
let expected = OperationResult::new("3 + 8", 11);
assert_eq!(response.into_json::<OperationResult>().unwrap(), expected);
}
}
//! This modules defines the possible operation and provide methods
//! to do the actual computation
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub enum Operation {
Plus(i32,i32),
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct OperationResult {
operation: String,
resultat: i32,
}
impl OperationResult {
/// Creates a new operation result from a [`&str`] and a value.
pub fn new(s: &str, value: i32) -> Self {
Self {
operation: String::from(s),
resultat: value,
}
}
}
impl From<&Operation> for OperationResult {
fn from(value: &Operation) -> Self {
match value {
Operation::Plus(op1, op2) => OperationResult {
operation: format!("{op1} + {op2}"),
resultat: op1 + op2,
}
}
}
}
impl From<Operation> for OperationResult {
fn from(value: Operation) -> Self {
OperationResult::from(&value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plus() {
let operation = Operation::Plus(4, 5);
let result = OperationResult::from(operation);
let expected = OperationResult::new("4 + 5", 9);
assert_eq!(result, expected);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment