Skip to content
This repository has been archived by the owner on Oct 4, 2021. It is now read-only.

How to use async database in on_message_create #1

Closed
Nerothos opened this issue May 26, 2020 · 2 comments
Closed

How to use async database in on_message_create #1

Nerothos opened this issue May 26, 2020 · 2 comments

Comments

@Nerothos
Copy link

Hi,

First, thanks for the lib!

I got a little problem, I need to be able to access my database pool in on_message_create (and probably others) but I can't pass parameters to the function that is passed in it :

client.on_message_create(message_manage(pool); because it ask me to pass Session<()> and MessageCreate which are passed by default

async fn message_manage(s: Session<()>, msg: MessageCreate, pool: MysqlPool) -> HandlerResult {

How would you to it? Can I get Session and MessageCreate at this moment and pass them "manually"?

@xyaman
Copy link
Owner

xyaman commented May 26, 2020

Hi, you can use a global state, using panda::new_with_state(), there is an example in example directory.

I don't know what library are you using, so take this as an idea.

struct GlobalState {
    database: MysqlPool
}


#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let state = GlobalState { database: MysqlPool::new("uri") };
    let mut client = panda::new_with_state("your token", state).await?;

    client.on_message_create(message_manage);

    client.start.await?;

    Ok(())
}

async fn message_manage(s: Session<GlobalState>, msg: MessageCreate ) ->  HandlerResult {

    let db_pool = &s.state.database;
    // if you need mutable you can use Mutex, in the state declaration.
    // for example, let state = GlobalState { datebase: Mutex::new(MysqlPool::new("uri")) }
    // Now you can use your db_pool

    Ok(())
}

@Nerothos
Copy link
Author

Thanks, I should have checked the examples again, I had this issue in a notepad for a moment, didn't thought it had with_state.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants