twitchtv / twirp

A simple RPC framework with protobuf service definitions
https://twitchtv.github.io/twirp/docs/intro.html
Apache License 2.0
7.2k stars 326 forks source link

Show flash message after successful operation #116

Closed zemirco closed 6 years ago

zemirco commented 6 years ago

I'm rewriting my REST API to twirp. So far so good.

In my old design I made a HTTP delete request, removed some item in the database, added a flash message to the user's session and redirected on the server. After the redirect the user was able to see the flash message. Try to delete some repository here at GitHub. You'll be redirected to the main page and see a message Your repository "zemirco/test" was successfully deleted..

session, err := c.SessionStore.Get(r, config.CookieName)
session.AddFlash("hello world.")
if err := c.SessionStore.Save(r, w, session); err != nil {
  ...
}
http.Redirect(w, r, r.URL.String(), http.StatusSeeOther)
return nil

Now I'm using React in my frontend and twirp for communication. I post a request, item is removed in the database, client gets the response and redirects on the frontend.

onDelete = async event => {
  event.preventDefault()
  await DeletePlayer('abc')
  window.location.href = `/${username}?tab=players`
}

I'd like to show the same flash message Your repository "zemirco/test" was successfully deleted. after the redirect. I'm stuck here since I do not have access to the request inside my twirp methods.

func (s *Server) DeleteItem(ctx context.Context, id *wrappers.StringValue) (*empty.Empty, error) {
  // no access to r here
}

How would you handle this situation? How do you add something to the user's current session? I'm using https://github.com/gorilla/sessions.

spenczar commented 6 years ago

If you want to communicate a message back to the client, the proper way to do it would be to have it in the response field. Instead of responding with Empty, have a DeleteItemResponse message which has a string field for the message to pass.

Then, the client unpacks the response from the server and can show the flash message however it likes.

Does that make sense? I'm not sure I totally understand the question.

spenczar commented 6 years ago

I'm going to close this as resolved. Let me know if you still have questions.