write method
Writes the session data to the underlying storage.
This method persists the session data using a storage mechanism like a
cookie, file, or database. It receives the request, response, and
session objects.
The request object provides context for the session. The response
object allows modifying the outgoing response (e.g., setting cookies).
The session object contains the data to be saved.
Returns a Future<void> that completes when the session is successfully
saved.
Example:
await store.write(request, response, session);
Implementation
@override
Future<void> write(
Request request,
Response response,
Session session,
) async {
final maxAgeSeconds =
session.options.maxAge ?? defaultOptions.maxAge ?? lifetime.inSeconds;
if (session.isDestroyed || maxAgeSeconds <= 0) {
_sessions.remove(session.id);
response.setCookie(
session.name,
'',
maxAge: 0,
path: session.options.path ?? defaultOptions.path ?? '/',
domain: session.options.domain ?? defaultOptions.domain ?? '',
);
return;
}
final payload = session.serialize();
final expiresAt = DateTime.now().add(Duration(seconds: maxAgeSeconds));
_sessions[session.id] = _MemorySession(payload, expiresAt);
final encoded = codecs.first.encode(session.name, {'id': session.id});
final cookieValue = Uri.encodeComponent(encoded);
response.setCookie(
session.name,
cookieValue,
maxAge: session.options.maxAge ?? defaultOptions.maxAge,
path: session.options.path ?? defaultOptions.path ?? '/',
domain: session.options.domain ?? defaultOptions.domain ?? '',
secure: session.options.secure ?? defaultOptions.secure ?? false,
httpOnly: session.options.httpOnly ?? defaultOptions.httpOnly ?? true,
sameSite: session.options.sameSite ?? defaultOptions.sameSite,
);
}