Created
May 9, 2022 01:56
-
-
Save eahrold/fb486e11dfb4c9963a9a129317d88e6f to your computer and use it in GitHub Desktop.
A micronaut HttpSessionResolver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import io.micronaut.http.HttpRequest; | |
import io.micronaut.http.context.ServerRequestContext; | |
import io.micronaut.session.Session; | |
import io.micronaut.session.SessionStore; | |
import io.micronaut.session.http.SessionForRequest; | |
import jakarta.inject.Singleton; | |
import java.util.Optional; | |
/** | |
* HttpSessionResolver | |
* @apiNote This is useful when needing to resolver the current Session | |
* without having to do method parameter binding. | |
* | |
* @implNote this should primarily be used in the @Controller level. | |
* Pass the `Session` forward into internal application calls. | |
* | |
*/ | |
@Singleton | |
public class HttpSessionResolver { | |
private final SessionStore<?> sessionStore; | |
public HttpSessionResolver(SessionStore<?> sessionStore) { | |
this.sessionStore = sessionStore; | |
} | |
public Optional<Session> getOrCreate() { | |
if(ServerRequestContext.currentRequest().isEmpty()) { | |
return Optional.empty(); | |
} | |
HttpRequest<?> request = ServerRequestContext.currentRequest().get(); | |
return Optional.of(SessionForRequest.findOrCreate(request, sessionStore)); | |
} | |
public Optional<Session> get() { | |
if(ServerRequestContext.currentRequest().isEmpty()) { | |
return Optional.empty(); | |
} | |
HttpRequest<?> request = ServerRequestContext.currentRequest().get(); | |
return Optional.of(SessionForRequest.findOrCreate(request, sessionStore)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment