欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Rust的MVC的微服务

程序员文章站 2022-06-06 10:14:50
...
#![feature(proc_macro_hygiene)]
#![feature(decl_macro)]

#[macro_use]
extern crate rocket;
use rocket_contrib::json::Json;

#[macro_use]
extern crate diesel;
extern crate dotenv;

mod controller;
mod domain;
mod dto;
mod repository;
mod schema;
mod service;

use controller::*;
use dto::*;
use repository::*;
use service::*;

#[post("/task/add", data = "<task>")]
fn task_add(task: Json<TaskDto>) {
    TaskController::new(TaskService::new(TaskRepository::new())).task_add(task);
}

fn main() {
    rocket::ignite().mount("/", routes![task_add]).launch();
}

 Controller mod.rs:

use crate::dto::*;
use crate::service::*;
use rocket_contrib::json::Json;

pub struct TaskController {
    service: TaskService,
}

impl TaskController {
    pub fn new(service: TaskService) -> TaskController {
        TaskController { service: service }
    }

    pub fn task_add(&self, task: Json<TaskDto>) {


        println!("task json format is {:?}",task);
        self.service.task_add(task.into_inner());
    }
}

 Service:

use crate::domain::*;
use crate::dto::*;
use crate::repository::*;
use chrono::{Utc, Local, DateTime, Date};

pub struct TaskService {
    repository: TaskRepository,
}

impl TaskService {
    pub fn new(repository: TaskRepository) -> TaskService {
        TaskService {
            repository: repository,
        }
    }

    pub fn task_add(&self, task: TaskDto) {
        let task2 = Task::new(task.get_name(), task.get_time_limit());


        println!("in service level is {:?}", task);
//        println!("in service level is {:?}",task2.ok());
        let local_date: Date<Local> = Local::today();




        let task_bak = Task { name: task.get_name().to_string(), time_limit: local_date };

        self.repository.task_add(task_bak);
    }
}

 Repo:

use crate::domain::*;
use crate::dto::*;
use crate::schema::task_models::dsl::*;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenv::dotenv;
use std::env;

pub struct TaskRepository {
    connection: PgConnection,
}

impl TaskRepository {
    pub fn new() -> TaskRepository {
        TaskRepository {
            connection: establish_connection(),
        }
    }

    pub fn task_add(&self, task: Task) {
        let _model = TaskModel::new(task);
        diesel::insert_into(task_models)
            .values(&_model)
            .execute(&self.connection)
            .expect("Error saving new task.");
    }
}

fn establish_connection() -> PgConnection {
    dotenv().ok();

    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url))
}

 

相关标签: Rust microservice