not working, basic structure with grpc

This commit is contained in:
filipriec
2025-02-15 22:57:40 +01:00
parent 9233c769b0
commit b871d40759
10 changed files with 352 additions and 80 deletions

View File

@@ -1,52 +1,27 @@
use tonic::{Request, Response, Status};
use sqlx::PgPool;
use multieko2::accounting_server::{Accounting, AccountingServer};
use multieko2::{CreateAccountRequest, CreateAccountResponse, GetAccountRequest, GetAccountResponse};
use crate::{db, proto::api::*};
pub struct MyAccountingService {
db_pool: PgPool,
pub struct AccountingService {
db_pool: sqlx::PgPool,
}
#[tonic::async_trait]
impl Accounting for MyAccountingService {
impl accounting_server::Accounting for AccountingService {
async fn create_account(
&self,
request: Request<CreateAccountRequest>,
) -> Result<Response<CreateAccountResponse>, Status> {
let name = request.into_inner().name;
let account = sqlx::query!("INSERT INTO accounts (name) VALUES ($1) RETURNING id", name)
.fetch_one(&self.db_pool)
.await
.map_err(|e| Status::internal(e.to_string()))?;
Ok(Response::new(CreateAccountResponse { id: account.id.to_string() }))
}
async fn get_account(
&self,
request: Request<GetAccountRequest>,
) -> Result<Response<GetAccountResponse>, Status> {
let id = request.into_inner().id;
let account = sqlx::query!("SELECT id, name FROM accounts WHERE id = $1", id)
.fetch_one(&self.db_pool)
.await
.map_err(|e| Status::internal(e.to_string()))?;
Ok(Response::new(GetAccountResponse {
id: account.id.to_string(),
name: account.name,
}))
// Database implementation
}
}
pub async fn run_server(db_pool: PgPool) -> Result<(), Box<dyn std::error::Error>> {
pub async fn run_server(pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
let addr = "[::1]:50051".parse()?;
let service = MyAccountingService { db_pool };
tonic::transport::Server::builder()
.add_service(AccountingServer::new(service))
.add_service(accounting_server::AccountingServer::new(
AccountingService { db_pool: pool }
))
.serve(addr)
.await?;
Ok(())
}