Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v3: cmdroute: Add Router.Group() #383

Open
labi-le opened this issue Mar 15, 2023 · 2 comments
Open

v3: cmdroute: Add Router.Group() #383

labi-le opened this issue Mar 15, 2023 · 2 comments
Labels
enhancement New feature or request

Comments

@labi-le
Copy link

labi-le commented Mar 15, 2023

I expect middleware to run for set and delete commands, but in fact I get this behavior for all commands. How can I concretize the execution of the middleware layer?

        bot.AddInteractionHandler(res)
        
	res.AddFunc("stats", res.Stats)
	res.AddFunc("help", res.Help)
	res.AddFunc("get", res.Get)
	res.AddFunc("search", res.Search)

	res.Use(res.CheckAccess)
	res.AddFunc("set", res.Set)
	res.AddFunc("delete", res.Delete)
@diamondburned
Copy link
Owner

There's currently no way to make Use only work for certain commands of the same level. Middlewares will always run before the command handler regardless of when they're added.

To do something like this, there should be a Group() function like go-chi:

res.AddFunc("search", res.Search)
res.Group(func(res *cmdroute.Router) {
    res.Use(res.CheckAccess)
    res.AddFunc("set", res.Set)
})

@diamondburned diamondburned changed the title How does the middleware work in this framework? v3: cmdroute: Add Router.Group() Mar 15, 2023
@diamondburned diamondburned added the enhancement New feature or request label Mar 15, 2023
@labi-le
Copy link
Author

labi-le commented Mar 15, 2023

simple trick

Wrap cmdroute.CommandHandlerFunc in another cmdroute.CommandHandlerFunc

res.AddFunc("set", res.CheckAccessMiddleware(res.Set))
func (r *resource) CheckAccessMiddleware(fn cmdroute.CommandHandlerFunc) cmdroute.CommandHandlerFunc {
	return func(ctx context.Context, data cmdroute.CommandData) *api.InteractionResponseData {
		interaction := data.Event.Data.(*discord.CommandInteraction)

		userID, err := ParseUserID(interaction.Options)
		if err != nil {
			return r.send(err.Error())
		}

		if !checkAccess(r.supportRoleID, data.Event.Member, userID) {
			return r.send(ErrNoAccess.Error())
		}

		return fn(ctx, data)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants