vaadin / hilla

Build better business applications, faster. No more juggling REST endpoints or deciphering GraphQL queries. Hilla seamlessly connects Spring Boot and React to accelerate application development.
https://hilla.dev
Apache License 2.0
922 stars 58 forks source link

How to use "middleware" to detect session expiration at client side? #1119

Open egloffmark opened 1 year ago

egloffmark commented 1 year ago

I try to follow the documentation about to use the "middleware" to detect the session expiration (link). But I don't understand how this "client" will connect and get informed about the expiration. I assume you need to call a "subscribe" after the "client" has been setup? Or does the "client" automatically subscribe somehow?


import { ConnectClient, InvalidSessionMiddleware } from '@hilla/frontend';
const client = new ConnectClient({
  prefix: 'connect',
  middlewares: [
    new InvalidSessionMiddleware(async () => {
    console.log("Session Expired !");
    ...
    }),
  ],
});

// what to do with the client ???
client.subscribe( ??? )
egloffmark commented 1 year ago

Ok, I found the documentation that you might have to modify the existing generated client here. However it looks like that the callback with InvalidSessionMiddleware only get called after the endpoint get called.

Is there a way to ensure that fist the session expiration get checked before the final endpoint get invoked?

import { InvalidSessionMiddleware, LoginResult } from '@hilla/frontend';
import client from 'Frontend/generated/connect-client.default';
if (client.middlewares) {
client.middlewares.push(
      new InvalidSessionMiddleware(async () => {
             console.log("Session Expired!");
             await userStore.logout();
             return {} as LoginResult;
               }),
    );
}

// calls implicit the generated client with the configured middleware 
let users = await BackendUserEndpoint.getAllUsers();