I'm learning rust, and I have been following the rust book. Usually, I try to implement something to strengthen my knowledge.
Recently I was looking into how to use the MongoDb create to create an instace and return the name of the database.
Here's a sample of what I have:
A folder containing a implementation to build a mongo connection string.
A .env file
A main function to get the info I need.
mongo_connection.rs
#[derive(Debug)]
pub struct ConnectionString {
pub username: String,
pub password: String,
pub cluster: String,
}
impl ConnectionString {
pub fn build_connection_string() -> String {
return format!("mongodb+srv://{}:{}#a{}.k1jklnx.mongodb.net/?retryWrites=true&w=majority",
Self.username, Self.password, Self.cluster)
}
}
main.rs
mod database;
use crate::database::mongo_connection;
use mongodb::{Client, options::ClientOptions};
use std::error::Error;
use dotenv::dotenv;
use std::env;
use tokio;
async fn create_database_connection() -> Client {
dotenv().ok(); //Loading environment variables from .env file
let connection_parameters = mongo_connection::ConnectionString{
username: env::var("USERNAME").expect("No username found on .env"),
password: env::var("PASSWORD").expect("No password found on .env"),
cluster: env::var("CLUSTER").expect("No cluster found on .env")
};
let mut url: String = mongo_connection::ConnectionString::build_connection_string();
println!("{}", url);
let options = ClientOptions::parse(&url).await?;
return Client::with_options(options).await;
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let client = create_database_connection().await?;
let db = client.database(&"runt");
println!("{:?}", db.name());
Ok(())
}
The problem I am facing is that I need to return a connection client. But I keep getting the Error:
let options = ClientOptions::parse(&url).await?;
^ cannot use the `?` operator in an async function that returns `Client`
If I change the result of the function to something like: Result<Client, dyn Eq> then I get the error:
async fn create_database_connection() -> Result<Client, dyn Eq> {
`Eq` cannot be made into an object
^^^^^^^^^^^^^^^ the trait cannot be made into an object because it uses `Self` as a type parameter
|
Any advice on how to solve the error or any workaround is much appreciated.
You could change the return type to either Result<Client, mongodb::error::Error> or Result<Client, Box<dyn Error>>. Either should work, but here's the code with the first version:
async fn create_database_connection() -> Result<Client, mongodb::error::Error> {
dotenv().ok(); //Loading environment variables from .env file
let connection_parameters = mongo_connection::ConnectionString{
username: env::var("USERNAME").expect("No username found on .env"),
password: env::var("PASSWORD").expect("No password found on .env"),
cluster: env::var("CLUSTER").expect("No cluster found on .env")
};
let mut url: String = mongo_connection::ConnectionString::build_connection_string();
println!("{}", url);
let options = ClientOptions::parse(&url).await?;
return Client::with_options(options).await;
}
In case you want to use the Box<dyn Error> version, the return value also needs a .into() to convert the Result<Client, mongodb::error::Error> of Client::with_options() into a Result<Client, Box<dyn Error>>.
Related
I have following Error:
error[E0277]: the trait bound `Bson: Borrow<News>` is not satisfied
--> src\handlers.rs:46:36
|
46 | let inserted = coll.insert_one(serialized_news, None).await.unwrap();
| ---------- ^^^^^^^^^^^^^^^ the trait `Borrow<News>` is not implemented for `Bson`
| |
| required by a bound introduced by this call
|
note: required by a bound in `mongodb::Collection::<T>::insert_one`
--> C:\Users\User\.cargo\registry\src\github.com-1ecc6299db9ec823\mongodb-2.3.1\src\coll\mod.rs:1279:19
|
1279 | doc: impl Borrow<T>,
| ^^^^^^^^^ required by this bound in `mongodb::Collection::<T>::insert_one`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `backend` due to previous error
My handler code containing the post_news function that throws this error:
use crate::structs::News;
use axum::{extract::Path, extract::State, http::StatusCode, response::IntoResponse, Json};
use bson::oid::ObjectId;
use futures::stream::StreamExt;
use mongodb::{bson::doc, options::FindOptions, Client, Collection};
pub async fn get_all(State(client): State<Client>) -> impl IntoResponse {
let coll: Collection<News> = client.database("axum").collection::<News>("news");
let mut options = FindOptions::default();
options.limit = Some(1);
options.sort = Some(doc! {
"title": 1
});
let mut cursor = coll
.find(None, options)
.await
.expect("could not load news data.");
let mut rows: Vec<News> = Vec::new();
while let Some(doc) = cursor.next().await {
rows.push(doc.expect("could not load news info."));
}
(StatusCode::OK, Json(rows))
}
pub async fn get_one(Path(id): Path<u64>) {}
pub async fn post_news(
State(client): State<Client>,
Json(payload): Json<News>,
) -> impl IntoResponse {
let coll: Collection<News> = client.database("axum").collection::<News>("news");
let news = News {
id: ObjectId::new(),
title: payload.title.to_string(),
short_description: payload.short_description.to_string(),
};
let serialized_news = bson::to_bson(&news).unwrap();
let inserted = coll.insert_one(serialized_news, None).await.unwrap();
(StatusCode::CREATED, Json(news))
}
pub async fn handler_404() -> impl IntoResponse {
(StatusCode::NOT_FOUND, "nothing to see here")
}
mod structs {
use bson::{self, oid::ObjectId};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct News {
#[serde(rename = "_id")]
pub id: ObjectId,
pub title: String,
pub short_description: String,
}
}
The error occurs in this line in the post_news function:
let inserted = coll.insert_one(serialized_news, None).await.unwrap();
Tried to add Clone and Debug to my struct and that didn't help
When encountering an error, you need to dig in and figure out why the error occurs, rather than just fiddling left and right.
In this case, the first step is looking at the function you are attempting to call Collection::insert_one:
pub async fn insert_one(
&self,
doc: impl Borrow<T>,
options: impl Into<Option<InsertOneOptions>>
) -> Result<InsertOneResult>
And double checking what Borrow is by following the link -- just to make sure it's indeed std::borrow::Borrow (spoiler: it is).
So, since your coll is of type Collection<News>, you need a type implementing Borrow<News> -- as mentioned by the error message -- which means amongst others News and &News.
Hence, as shown in the documentation of Collection, you should just insert your News object, without first serializing it:
let inserted = coll.insert_one(news, None).await.unwrap();
Collection will take care of serializing and deserializing as appropriate, no need to do the bson step yourself.
This is my async function that uses rust to connect to an existing mongoDB database. Is there a way to return / export the client variable / object and make it usable in other Files / Functions?
async fn connect_to_db() -> Result<(), Box<dyn Error>> {
// Load the MongoDB connection string from an environment variable (or string):
let client_uri = "mongodb://localhost:27017";
let options =
ClientOptions::parse_with_resolver_config(&client_uri, ResolverConfig::cloudflare())
.await?;
let client = Client::with_options(options)?;
let db = client.database("fiesta");
// Select Collection(s)
let user_col: Collection<User> = db.collection("users");
let skills_col: Collection<Skill> = db.collection("skills");
//ok.
Ok(())
}
Help would be appreciated.
Dependencies:
rocketrs
mongodb
tokio & serde
I have tried multiple things such as changing the lifetimes and changing the return type of the function, but to no avail.
I just want to get a JSON from the following URL.
So I used this code:
extern crate reqwest;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let res = reqwest::Client::new()
.get("https://api.github.com/users/octocat")
.send()?
.text()?;
println!("{}", res);
Ok(())
}
But I don't know how to solve the error :
error[E0277]: the `?` operator can only be applied to values that implement `std::ops::Try`
--> src\main.rs:19:15
|
19 | let res = reqwest::Client::new()
| _______________^
20 | | .get("https://api.github.com/users/octocat")
21 | | .send()?
| |________________^ the `?` operator cannot be applied to type `impl std::future::Future`
|
= help: the trait `std::ops::Try` is not implemented for `impl std::future::Future`
= note: required by `std::ops::Try::into_result`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: could not compile `Desktop`.
but I can also obtain what I want with a simple
curl https://api.github.com/users/octocat
I've tried to add use std::ops::Try; but it doesn't work better.
The reqwest crate uprovides an asynchronous api by default. Therefore you have to .await before handling the error with the ? operator. You also have to use an async runtime, such as tokio:
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.get("https://api.github.com/users/octocat")
.send()
.await?
.json::<std::collections::HashMap<String, String>>()
.await?;
println!("{:#?}", resp);
Ok(())
}
Note that to use convert the response to json as shown above, you must enable the json feature in your Cargo.toml:
reqwest = { version = "0.10.8", features = ["json"] }
If you don't want to use an async runtime, you can enable the blocking reqwest client:
[dependencies]
reqwest = { version = "0.10", features = ["blocking", "json"] }
And use it like so:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::blocking::Client::new()
.get("https://api.github.com/users/octocat")
.send()?
.json::<std::collections::HashMap<String, String>>()?;
println!("{:#?}", resp);
Ok(())
}
Github's api requires a couple other config options. Here is a minimal working example with reqwest and the github api:
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};
use serde::{Deserialize};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut headers = HeaderMap::new();
// add the user-agent header required by github
headers.insert(USER_AGENT, HeaderValue::from_static("reqwest"));
let resp = reqwest::blocking::Client::new()
.get("https://api.github.com/users/octocat")
.headers(headers)
.send()?
.json::<GithubUser>()?;
println!("{:#?}", resp);
Ok(())
}
// Note that there are many other fields
// that are not included for this example
#[derive(Deserialize, Debug)]
pub struct GithubUser {
login: String,
id: usize,
url: String,
#[serde(rename = "type")]
ty: String,
name: String,
followers: usize
}
I'm trying to create an API using Actix-web, async-grahpql and sqlx with postgresql
In the QueryRoot of the async-graphql I am trying to capture the reference of the DB and make the query the database with sqlx, but it gives me an error
let items = Todo::list(&pool).await?;
| ^^^^^ expected struct `sqlx::Pool`, found enum `std::result::Result`
Here I want to capture the reference
use crate::todo::*;
use async_graphql::{Context, FieldResult};
use sqlx::postgres::PgPool;
pub struct QueryRoot;
#[async_graphql::Object]
impl QueryRoot {
async fn todos(&self, ctx: &Context<'_>) -> FieldResult<Vec<Todo>> {
let pool = ctx.data::<PgPool>();
let items = Todo::list(&pool).await?; //<-- This line generates an error
Ok(items)
}
}
Here I define the references
pub fn run(listener: TcpListener, db_pool: PgPool) -> Result<Server, std::io::Error> {
let data_db_pool = Data::new(db_pool);
//GraphQL
let schema = Schema::build(QueryRoot, MutationRoot, EmptySubscription)
.data(data_db_pool.clone()) //<- DB reference
.finish();
let server = HttpServer::new(move || {
App::new()
.app_data(db_pool.clone()) //<- DB reference
.data(schema.clone())
.route("/graphql", web::post().to(graphql))
.route("/graphql", web::get().to(graphql_playground))
})
.listen(listener)?
.run();
Ok(server)
}
What am I doing wrong? The complete code can be found here.
ctx.data::<T>() returns a Result wrapping a reference to T. You probably want.
let pool = ctx.data::<PgPool>()?;
// ^ return on Err, otherwise yield the &PgPool
let items = Todo::list(pool).await?;
// ^^^^ shouldn't need & here
Trying to make server with actix-web & mongodb in rust. Getting error
the trait std::convert::From<mongodb::error::Error> is not implemented for std::io::Error
here is my code
use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use mongodb::{options::ClientOptions, Client};
async fn greet(req: HttpRequest) -> impl Responder {
let name = req.match_info().get("name").unwrap_or("World");
format!("Hello {}!", &name)
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
// Parse a connection string into an options struct.
let mut client_options = ClientOptions::parse("mongodb://localhost:27017")?;
// Manually set an option.
client_options.app_name = Some("My App".to_string());
// Get a handle to the deployment.
let client = Client::with_options(client_options)?;
// List the names of the databases in that deployment.
for db_name in client.list_database_names(None)? {
println!("{}", db_name);
}
HttpServer::new(|| {
App::new()
.route("/", web::get().to(greet))
.route("/{name}", web::get().to(greet))
})
.bind("127.0.0.1:8000")?
.run()
.await
}
Did I missed anything?
It means that one of the functions you are calling with a ? at the end can return a mongodb::error::Error. But the signature of the main is a std::io::Result<()>, wich is an implied Result<(), std::io::Error>. The only error type it can accept is a io::Error, not a mongodb::Error.
It looks like all the functions you are escaping might return this mongodb::error::Error, so you can try to change the main signature to such a result: Result<(). mongodb::error::Error>.
But I would recommend you do proper error handling on those potential errors, as this is your main(). Change those ? to .expect("Some error message"); at least. The program will still crash, but it will crash in a way that is meaningful to you.