owengombas / discord.ts

🤖 Create your discord bot by using TypeScript and decorators!
https://owencalvin.github.io/discord.ts/
325 stars 40 forks source link

cannot use dynamic prefix with Mysql #45

Closed JuanJoZP closed 3 years ago

JuanJoZP commented 3 years ago

Hi. with mysql I have to return the results of a query througth a callback, but the Discord decorator doesn't accept that. I dont know how can i get the value that is passed to callback out of its scope in order to use it in the Discord decorator.

const getPrefix = (callback: (result: string) => void) => {
  connection.query("SELECT prefix FROM config", (err, rows) => {
    if (err) throw err

    if (rows[0]?.prefix !== undefined) {
      callback(rows[0].prefix)
    } else {
      callback("!")
    }
  })
}

@Discord(getPrefix)
SteeledSlagle13 commented 3 years ago

your get prefix function should be async https://github.com/OwenCalvin/discord.ts#dynamic-values

and follow this approach

JuanJoZP commented 3 years ago

thank you, I solved it making the function async and returning a promise that resolves a string

const getPrefix = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    connection.query("SELECT prefix FROM config", (err, rows) => {
      if (err) reject(err)

      if (rows[0]?.prefix !== undefined) {
        resolve(rows[0].prefix)
      } else {
        resolve("!")
      }
    })
  })
}

@Discord(getPrefix, {