How to intercept calls #6034
|
Hi. I would like to intercept wails call (method calls), so before every call I would like to open a db transaction, and after the call, if there is no error, commit the transaction and close the db. Is it possible? I cannot find anything like that in wails. I also need to log the error message when error happens on call and roll back the transaction. Something like this: type App struct { ctx context.Context }
func (b *App) startup(ctx context.Context) { b.ctx = ctx }
func (b *App) shutdown(ctx context.Context) {}
func (b *App) Greet(name string) string { return fmt.Sprintf("Hello %s!", name) }
func (b *App) before_method_call()
{
b.db.OpenTransaction()
}
func (b *App) after_method_call(err error)
{
if err == nil
{
b.db.Commit()
}
else
{
b.db.Rollback()
b.log.Error(err)
}
}Any ideas how I can achieve that? I cannot find anything in the documentation (https://wails.io/docs/next/howdoesitwork). I also would like to intercept calls in frontend. If that's also possible. |
Replies: 1 comment 1 reply
|
There's no hook for this in Wails, and the thing you'll find if you go searching for one is a trap. The reason nothing exists is that bindings are generated by reflecting over your struct's exported methods and then invoked directly. There's no chain to insert yourself into. What I'd do instead is keep the transaction in a helper the bound methods call through: func (a *App) withTx(fn func(*sql.Tx) error) error {
tx, err := a.db.Begin()
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p)
}
}()
if err := fn(tx); err != nil {
tx.Rollback()
a.log.Error(err)
return err
}
return tx.Commit()
}Each bound method then costs one line of ceremony: func (a *App) CreateUser(name string) error {
return a.withTx(func(tx *sql.Tx) error {
_, err := tx.Exec("INSERT INTO users(name) VALUES(?)", name)
return err
})
}If you need a value back rather than just an error, a generic version of Worth pushing on the requirement a little though, because a transaction around every call would bite you even if you could have it. On the frontend, the generated bindings in |
There's no hook for this in Wails, and the thing you'll find if you go searching for one is a trap.
Middlewarein Wails lives underpkg/options/assetserverand wraps the asset server's HTTP handler. Bound method calls never travel through it, so it reads like the answer and isn't.The reason nothing exists is that bindings are generated by reflecting over your struct's exported methods and then invoked directly. There's no chain to insert yourself into.
What I'd do instead is keep the transaction in a helper the bound methods call through: