You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently, session-data is stored as type "Any?".
It would be great to have session-data stored in a type-safe way.
At the moment, I have implemented these extension functions to satisfy my requirement:
/** * Enables session support for storing arbitrarily typed data. * @param initGenerator specifies how session-data is initialized * @return An object to retrieve the data in a type-safe way.*/fun <T> AppServer.enableTypesafeSessionSupport( initGenerator: (Request) ->T ) : SessionFetcher<T> {
enableSessionSupport()
returnSessionFetcher<T>(initGenerator)
}
/** * Enables session support for storing arbitrarily typed data. * @return An object to retrieve the data in a type-safe way.*/fun <T> AppServer.enableTypesafeSessionSupport() : SessionFetcher<T?> {
return enableTypesafeSessionSupport({null})
}
classSessionFetcher<T> internal constructor(valinitGenerator: (Request) ->T ) {
protectedval values =ConcurrentHashMap<String,T>()
operatorfunget(request:Request) : T {
// session must to be there, because session-fetcher is internally created onlyval key = request.session!!.id
return values.getOrPut( key, { initGenerator(request) } )
}
}
This can then for example be used like this:
data classSessionData (
varuserId:Int? = null// here you may put further stuff to be type-safely stored,// for example persisted data of a database or even write functions for retrieving them
)
// easy-access extension-functionvalRequest.tSession:SessionData
get() =MyApp.sessionDataFetcher[this]
// application exampleobject MyApp {
val sessionDataFetcher:SessionFetcher<SessionData>
privateval server :AppServerinit {
server =AppServer()
sessionDataFetcher = server.enableTypesafeSessionSupport { SessionData() }
server.get("/", {
response.send("Your user id is ${request.tSession.userId.toString()}")
})
server.get("/set", {
request.tSession.userId =Random().nextInt()
response.send("Your user id has been randomly set.")
})
server.addStyleSheet(MainCss(),true)
}
@JvmStatic funmain(args:Array<String>) {
server.start()
}
}
The text was updated successfully, but these errors were encountered:
It would be great to have this or some other kind of type-safety for session-data introduced into the SessionManagementInterceptor, because when you use the code this way, we create multiple concurrent hash maps.
Currently, session-data is stored as type "Any?".
It would be great to have session-data stored in a type-safe way.
At the moment, I have implemented these extension functions to satisfy my requirement:
This can then for example be used like this:
The text was updated successfully, but these errors were encountered: