yznts / kyoto

Asynchronous frontends with Go
https://pkg.go.dev/github.com/yznts/kyoto/v3
MIT License
651 stars 28 forks source link

Question - set cookie on response to SSA call #35

Closed c-nv-s closed 3 years ago

c-nv-s commented 3 years ago

How is it possible to access the request context from a call to a Server-Side Action. Say, for instance you want to set a cookie in the response to an SSA call.

In the example demo app for the form submission example (email validator) you have the following:

type ComponentDemoEmailValidator struct {
    Email   string
    Message string
    Color   string
}

func (c *ComponentDemoEmailValidator) Actions() ssc.ActionMap {
    return ssc.ActionMap{
        "Submit": func(args ...interface{}) {
            if emailregex.MatchString(c.Email) {
                c.Message = "Provided email is valid"
                c.Color = "green"
            } else {
                c.Message = "Provided email is not valid"
                c.Color = "red"
            }
        },
    }
}

I am aware you can create an "Init" method function to access the request context i.e.

func (c *ComponentDemoEmailValidator) Init(p ssc.Page) {
    c.Page = p
    r := ssc.GetContext(p, "internal:r").(*http.Request)
    rw := ssc.GetContext(p, "internal:rw").(http.ResponseWriter)
}

But how do you access the request/response context from within the "Actions()" method so that you can, for example, set a cookie in the response. Is this possible?

yznts commented 3 years ago

You’ll need to define init method, just like in example, and assign page as a component field (in the example, it’s c.Page = p. After that, in the action you can access page instance with c.Page. So, for getting context in action you can use ssc.GetContext(c.Page, “internal:r”)

yznts commented 3 years ago

It’s a bit complex, so I’m in search of better way to handle that

yznts commented 3 years ago

@c-nv-s
With latest release, I've implemented methods overloading and tried to rework documentation a bit. I hope, this will help you :) Actions usage documentation can be found here: https://ssceng.codes/docs/extended-features.html#ssa-usage Methods overloading documentation can be found here: https://ssceng.codes/docs/concepts.html#methods-overloading

TL;DR Now you can define your actions method in this way (it's completely optional):

...
func (c *ComponentExample) Actions(p ssc.Page) ssc.ActionMap {
    ...
}
...

Closing issue for now. If you have more questions or need support, please contact me directly with email/telegram, or open new issue. Have a good day!